ASP.NET MVC Auxiliary method is used to generate a drop -down list for the attributes in the model. When the model attribute is an array or collection, the drop -down list will be presented to each item in the array or collection.
However, when the value is in the array or set, the selection value of the drop -down list may be tricky. By default, the selected value will be based on the first settings in the array or collection. @Html.DropDownListFor
Method 1: Use the editor template
Create a custom editor template for the type in the collection. Create a part of the view in , including the following code:
Then in the main view, send Selectlist as an additional ViewData to the editor template:
Views/Shared/EditorTemplates/AggregationLevelConfiguration.cshtml
<code class="language-csharp">@model yourAssembly.AggregationLevelConfiguration @Html.DropDownListFor(m => m.HelperCodeType, (SelectList)ViewData["CodeTypeItems"]) .... // AggregationLevelConfiguration的其他属性</code>
In this method, set the
<code class="language-csharp">@using (Html.BeginForm()) { ... @Html.EditorFor(m => m.Configurations , new { CodeTypeItems = Model.CodeTypeItems }) ... }</code>
rather than . Then in the main view, generate a new :
CodeTypeItems
IEnumerable<genericidnametype>
Please note that this method is only applicable to the first element of the SelectList
array. For other elements in the array, cycle treatment is required and Configurations
is generated for each element. This may need to use the circular structure (such as SelectList
cycle or cycle) to iterate the array, and generate a new
<code class="language-csharp">@Html.DropDownListFor(m => m.Configurations[0].HelperCodeType, new SelectList(Model.CodeTypeItems, "Id", "Name", Model.Configurations[0].HelperCodeType))</code>
The above is the detailed content of How to Set the Selected Item in an MVC5 Razor @Html.DropDownListFor when the Value is in an Array?. For more information, please follow other related articles on the PHP Chinese website!