I have a simple piece of code that tries to populate a list of 3 countries and select the 2nd item by default. For some reason, @Html.DropDownList is not initializing the 2nd item in the screen. Can someone point out whats wrong with this code ?
public class DemoController : Controller
{
[HttpGet]
public ActionResult Test()
{
List<SelectListItem> ddlCountries = new List<SelectListItem>();
SelectListItem item1 = new SelectListItem { Selected = false, Text = "USA", Value = "1" };
SelectListItem item2 = new SelectListItem { Selected = true, Text = "Ireland", Value = "2" };
SelectListItem item3 = new SelectListItem { Selected = false, Text = "UK", Value = "3" };
ddlCountries.Add(item1);
ddlCountries.Add(item2);
ddlCountries.Add(item3);
ViewBag.ddlCountries = ddlCountries;
return View();
}
[HttpPost]
public string Test(string ddlCountries)
{
return "The selected Value was " + ddlCountries;
}
}
The below is the output on the screen..
The quickwatch window shows that the "Selected" property is correctly set to value "2", yet the screen doesn't reflect this..
The code for the view is the following
@{
ViewBag.Title = "Test";
}
<h2>Test</h2>
@using (Html.BeginForm("Test", "Demo", FormMethod.Post))
{
@Html.DropDownList("ddlCountries", (IEnumerable<SelectListItem>) ViewBag.ddlCountries)
<br />
<input type="submit" value="submit" />
}
Try using a view model, it's much easier, safer and cleaner:
and then in your controller:
and finally in your strongly typed view:
and that's pretty much the correct approach. Forget about any ViewBag stuff. Just use a view model. The single source of information for the view must be the view model.
By the way the GET controller action could be simplified to:
or the countries could be directly bound in your view model:
and then your controller becomes even slimmer: