In MVC web app it is a view with strongly typed model where a drop down is being generated / bind by model.
Below is view code:
@model LoanViewModel
A simple example of using Html.DropDownFor()
to display a list of options and bind to a property:
Model
public class LoanViewModel
{
[Required]
[Display(Name="Select Item")]
public string Item { get; set; }
public SelectList ItemList { get; set; }
}
Controller
public ActionResult Edit()
{
LoanViewModel model = new LoanViewModel();
model.Item = "Two"; // this will now pre-select the second option in the view
ConfigureEditModel(model);
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(LoanViewModel model)
{
if (!ModelState.IsValid)
{
ConfigureEditModel(model); // repopulate select list
return View(model); // return the view to correct errors
}
// If you want to validate the the value is indeed one of the items
ConfigureEditModel(model);
if (!model.ItemList.Contains(model.Item))
{
ModelState.AddModelError(string.Empty, "I'm secure!");
return View(model);
}
string selectedItem = model.Item;
....
// save and redirect
}
private void ConfigureEditModel(LoanViewModel model)
{
List<string> items = new List<string>() { "One", "Two", "Three" };
model.ItemList = new SelectList(items); // create the options
// any other common stuff
}
View
@model LoanViewModel
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@Html.DisplayFor(m => m.Item)
@Html.DropDownListFor(m => m.Item, Model.ItemList), "--Choose any Item--")
@Html.ValidationMessageFor(m => m.Item)
<input type="submit" value="Submit" />
}