In ASP.NET MVC5, use@html.dropdownListfor to process the array value as the selection of the drop -down table
In ASP.NET MVC 5, the
Auxiliary method is used to render the drop -down list for the attributes in the model. However, sometimes you may need to set the selection value of the drop -down list based on the value of the array or set in the model.
@Html.DropDownListFor()
Consider the following example:
In this example, <code class="language-csharp">@Html.DropDownListFor(m => m.Configurations[0].HelperCodeType, (SelectList)Model.HelperCodeTypeItems, new { id = "Configurations[0].HelperCodeType" })</code>
Copy after login
attribute is an array of object. We hope to set the selection value of the drop -down list according to the Configurations
attribute of the first element in the array. AggregationLevelConfiguration
Configurations
However, if we try to use the following code to set the selection value of the drop -down list: HelperCodeType
We will encounter errors. This is because the
constructor expects the fourth parameter is the string, but the <code class="language-csharp">new SelectList(Model.HelperCodeTypeItems, "Id", "Name", Model.Configurations[0].HelperCodeType)</code>
Copy after login
attribute is byte type.
SelectList
In order to solve this problem, we can use one of the following two methods: Model.Configurations[0].HelperCodeType
Method 1: Use Editortemplate
Create a custom for type. In , we can use the auxiliary method to render the drop -down list as the
attribute. We can also set the selection value of the drop -down list according to the attribute.
AggregationLevelConfiguration
For example, set the selection value of the drop -down list below to EditorTemplate
attributes of the EditorTemplate
object: @Html.DropDownListFor()
HelperCodeType
Model.HelperCodeType
Method 2: Generate a new SELECTList
EditorTemplate
In this method, we will generate a new Model
object for each element in the HelperCodeType
array. Then, we can set the selection value of the drop -down list according to the current element's
attribute. <code class="language-csharp">@model yourAssembly.AggregationLevelConfiguration
@Html.DropDownListFor(m => m.HelperCodeType, (SelectList)ViewData["CodeTypeItems"])
.... // AggregationLevelConfiguration的其他属性</code>
Copy after login
For example, the following code will generate a new object for each element in the array in the array:
Both methods allow us to set the selection value of the drop -down list based on the value of the array or collection in the model. Configurations
The above is the detailed content of How to Select a Value in an ASP.NET MVC5 @Html.DropDownListFor When the Value is in an Array?. For more information, please follow other related articles on the PHP Chinese website!