In the ASP.NET MVC 5 application, the auxiliary method can be used to generate a drop -down list from a data set. However, when processing complex data structures (such as array), setting the selection value according to the attributes in the array may bring challenges.
Consider the following ViewModel:
@Html.DropDownListFor()
attribute of the
object in the@model MyProject.Web.API.Models.AggregationLevelConfViewModel @Html.DropDownListFor(m => m.Configurations[0].HelperCodeType, (SelectList)Model.HelperCodeTypeItems, new { id = "Configurations[0].HelperCodeType" })
The conventional method of setting the selection value in the constructor is invalid, because the selection value that is not available in the Configurations
collection. AggregationLevelConfiguration
HelperCodeType
<决> Solution: SelectList
HelperCodeTypeItems
Create an editor template in <创>:
Then, in the main view, use to pass
to the editor template:
/Views/Shared/EditorTemplates/AggregationLevelConfiguration.cshtml
@model yourAssembly.AggregationLevelConfiguration @Html.DropDownListFor(m => m.HelperCodeType, (SelectList)ViewData["CodeTypeItems"])
additionalViewData
set <为> SelectList
instead of
@using (Html.BeginForm()) { ... @Html.EditorFor(m => m.Configurations , new { CodeTypeItems = Model.CodeTypeItems }) ... }
Please note that The attribute is automatically generated by without manual specification.
The above is the detailed content of How to Set the Selected Value in @Html.DropDownListFor When the Value Is in an Array?. For more information, please follow other related articles on the PHP Chinese website!