Setting Selected Items in MVC DropDownListFor

To set the selected item for a DropDownListFor in MVC, you can use a SelectListItem object in the view to specify the value of the selected item. The specific steps are as follows:

  1. Prepare a data source in the controller, such as a list data source or a data source retrieved from a database.
  2. Use the DropDownListFor method in the view to create a dropdown list, passing in the data source and the selected item’s value.

The sample code is as follows:

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        List<SelectListItem> items = new List<SelectListItem>
        {
            new SelectListItem { Text = "Option 1", Value = "1" },
            new SelectListItem { Text = "Option 2", Value = "2" },
            new SelectListItem { Text = "Option 3", Value = "3" },
        };

        ViewBag.Options = items;

        ViewBag.SelectedOption = "2"; // 设置选中项的值为2

        return View();
    }
}

perspective:

@Html.DropDownListFor(m => m.SelectedOption, ViewBag.Options as List<SelectListItem>)

In the above code, we first prepare a dropdown list data source ‘items’ in the controller and store it in ViewBag. Then, we set the selected item value to “2” and finally use the DropDownListFor method in the view to create the dropdown list, specifying the selected item value as “2”. This will default to selecting the second option when the page loads.

bannerAds