Home > Net >  ASP.NET MVC pre-selected Html.DropDownListFor
ASP.NET MVC pre-selected Html.DropDownListFor

Time:05-21

I have problem with Html.DropDownListFor. I have read a lot of similar enter image description here

CodePudding user response:

ViewBag.OptionsMeals = new List<SelectListItem>
{ 
  new SelectListItem{Text="aa", Value="0"},
  new SelectListItem{Text="bb", Value="1",Selected=true},      
  new SelectListItem{Text="cc", Value="2"}
}

With @Html.DropDownList()

@Html.DropDownList("OptionMeals", (List<SelectListItem>)ViewBag.OptionsMeals)

With @Html.DropDownListFor()

@Html.DropDownListFor(x => x.MealName, (List<SelectListItem>)ViewBag.OptionsMeals)

Sample: https://dotnetfiddle.net/hHJrWs

CodePudding user response:

DropDownListFor requires the View to have a Model (strongly typed), and uses the values in the Model to populate the relevant fields.

So you need to add

@model OrderForm 

to the top of your view page.

Then pass the order into the View in the controller

var order = mealService.GetMeal(id);
View(order)

and the MealName field will now be populated successfully.

@Html.DropDownListFor(x => x.MealName,(List<SelectListItem>)ViewBag.OptionsMeals)
  • Related