[RESOLVED]mvc4 how can i create a dropdownlist in controller

I basically would like to know how can I create a list in a controller; for example I have this small list in a view

@Html.DropDownList("postedstate", new SelectList(
     new List<Object>{
          new { Text = "West Virginia", Value = "WV"},
          new { Text = "Wyoming", Value = "WY"},
     }, "Value", "Text"))

How can I now create this same list inside a controller or a List object. I been searching and can not seem to figure it out any help would be great

You can try with the below implementation

Model:

public class SampleViewModel
	{
		
		 [Display(Name = "Cars")]
		 public SelectList Cars { get; set; }
	}
	

Controller Code:

public class HomeController : Controller
	{
		[HttpGet]
		public ActionResult Index()
		{
			
			SampleViewModel model = new SampleViewModel();

            List<SelectListItem> listItems = new List<SelectListItem>();
            listItems.Add(new SelectListItem()
            {
                Value = "111",
                Text = "Car1"
            });
            listItems.Add(new SelectListItem()
            {
                Value = "222",
                Text = "Car2"
            });
            listItems.Add(new SelectListItem()
            {
                Value = "3333",
                Text = "Car3",
                //Selected=true
            });
            model.Cars = new SelectList(listItems, "Value", "Text");
            return View(model);

			
			//return View(new SampleViewModel());
		}
	}

View:

@using (Html.BeginForm())
				{
					<div class="form-group">
					   @Html.DropDownList("Cars", Model.Cars)
					</div>	
				}

Thank you that worked

romeo407

Thank you 

You are welcome

Leave a Reply