Use@html.dropdownListfor to set the medium value of the array in the asp.net MVC 5 in ASP.NET MVC 5
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<code class="language-csharp">@model MyProject.Web.API.Models.AggregationLevelConfViewModel @Html.DropDownListFor(m => m.Configurations[0].HelperCodeType, (SelectList)Model.HelperCodeTypeItems, new { id = "Configurations[0].HelperCodeType" })</code>
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
<code class="language-csharp">@model yourAssembly.AggregationLevelConfiguration @Html.DropDownListFor(m => m.HelperCodeType, (SelectList)ViewData["CodeTypeItems"])</code>
additionalViewData
set SelectList
instead of
<code class="language-csharp">@using (Html.BeginForm()) { ... @Html.EditorFor(m => m.Configurations , new { CodeTypeItems = Model.CodeTypeItems }) ... }</code>
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!