In MVC, when a strong type editing page is involved, if a select element exists, you need to Select a select item based on a certain attribute value of the current Model. This article only organizes ideas and does not involve complete code.
□Ideas
The type of the forward view is List <SelectListItem>. Set the Selected Attribute of the Selected SelectListItem to true, and put the object instance of this type in ViewBag, ViewData or Model to the foreground view.
□Controller
public ActionResult SomeAction(int id)
{
// Obtain the Domain Model from the database
var domainModel = ModelService.LoadEntities(m => m.ID == id).FirstOrDefault<Model>();
// Obtain the List <SelectListItem> type object instance using a method
List<SelectListItem> items = SomeMethod();
// Traverses the set. If an attribute of the current Domain model is the same as the Value attribute of SelectListItem, set the Selected Attribute of SelectListItem to true.
foreach(SelectListItem item in items)
{
If (item. Value = Convert. ToString (domainModel. An Attribute ))
{
item.Selected = true;
}
}
// Put the List <SelectListItem> set object instance into ViewData
ViewData["somekey"] = items;
// It may involve converting Domain Model to View Model
return PartialView(domainModel);
}
□Foreground View display
@ Model DomainModel
@ Html. DropDownListFor (m => m. SomeProperty, (List <SelectListItem>) ViewData ["somekey"], "= select = ")
Set a bool field for View Model to check whether the field is selected.
Some attributes of the Model are used as the Text and Value values of SelectListItem. Determine whether to set SelectListItem's Selected to true based on the Boolean attribute in View Model.
□View Model
public class Department
{
public int Id {get;set;}
public string Name {get;set;}
public bool IsSelected {get;set;}
}
□Controller
public ActionResult Index()
{
SampleDbContext db = new SampleDbContext();
List<SelectListItem> selectListItems = new List<SelectListItem>();
// Traverse the Department set
foreach(Department department in db.Departments)
{
SelectListItem = new SelectListItem
{
Text = department.Name,
Value = department.Id.ToString(),
Selected = department.IsSelected.HasValue ? department.IsSelected.Value : false
}
selectListItems.Add(selectListItem);
}
ViewBag.Departments = selectListItems;
return View();
}