In the ASP.NET MVC 5 application, how to use the selection value in the MVC5 Razor Html.DropDownListFor
?
Problem description
In the ASP.NET MVC 5 application, the goal is to use the value of the
array (especially and Configurations
fields) to set the selection value of AggregationLevelConfiguration.CodeType
and AggregationLevelConfiguration.HelperCodeType
attributes. However, the selection value cannot be set using or CodeTypeItems
. HelperCodeTypeItems
new SelectList(codeTypes, "Id", "Name")
Solution new SelectList(helperCodeTypes, "Id", "Name")
Plan 1: Use Editortemplate
Create a customized EditortEmplate, such as , such as:
Then in the main view, transmit Selectlist as an additional view data to Editortemplate:
AggregationLevelConfiguration
AggregationLevelConfiguration
Solution 2: Selectlist AggregationLevelConfiguration.cshtml
<code class="language-csharp">@model yourAssembly.AggregationLevelConfiguration @Html.DropDownListFor(m => m.HelperCodeType, (SelectList)ViewData["CodeTypeItems"]) .... // AggregationLevelConfiguration的其他属性</code>
and set
variables to public attributes. Then use the following code in the main view:<code class="language-csharp">@using (Html.BeginForm()) { ... @Html.EditorFor(m => m.Configurations , new { CodeTypeItems = Model.CodeTypeItems }) ... }</code>
Please note that using is unnecessary, because the
method will automatically generate attributes. CodeTypeItems
IEnumerable<genericidnametype>
This Revised Response Offers A More Concise and Clearer Explanation of the Problem and Solutions, While Maintaining the Original Image. matted for better readability. codeTypes
The above is the detailed content of How to Set Selected Values in MVC5 Razor `Html.DropDownListFor` When Values are in an Array?. For more information, please follow other related articles on the PHP Chinese website!