To set an item as selected when an ASP.NET MVC DropDownList is loaded, you can pass the selected item's value to the view and then use that value to set the selected attribute for the corresponding option in the DropDownList. Here's an example of how you can achieve this:
- In the controller action, retrieve the list of items for the DropDownList and set the selected item's value:
public ActionResult Index()
{
// Get the list of items for the DropDownList
List<SelectListItem> items = GetDropDownListItems();
// Set the selected item's value
string selectedValue = "2"; // Set your desired selected value here
items.FirstOrDefault(item => item.Value == selectedValue)?.Selected = true;
// Pass the items to the view
ViewBag.Items = items;
return View();
}
- In the view, render the DropDownList using the ViewBag and iterate through the items to set the selected attribute:
@{
var items = ViewBag.Items as List<SelectListItem>;
}
@Html.DropDownList("myDropDownList", items)
Make sure to replace "myDropDownList"
with the appropriate name for your DropDownList. The DropDownList helper will automatically generate the options and set the selected attribute based on the selected property of the SelectListItem.
That's it! When the view is rendered, the option with the selected value will be displayed as selected in the DropDownList.
Top comments (0)