在ASP.NET MVC 5應用程序中,如何使用數組值設置MVC5 Razor Html.DropDownListFor
中的選中值?
問題描述
在ASP.NET MVC 5應用程序中,目標是使用Configurations
數組中的值(特別是AggregationLevelConfiguration.CodeType
和AggregationLevelConfiguration.HelperCodeType
字段)來設置CodeTypeItems
和HelperCodeTypeItems
屬性的選中值。然而,使用new SelectList(codeTypes, "Id", "Name")
或new SelectList(helperCodeTypes, "Id", "Name")
無法設置選中值。
解決方案
方案一:使用EditorTemplate
為名為AggregationLevelConfiguration
的AggregationLevelConfiguration
創建一個自定義EditorTemplate,例如AggregationLevelConfiguration.cshtml
:
@model yourAssembly.AggregationLevelConfiguration @Html.DropDownListFor(m => m.HelperCodeType, (SelectList)ViewData["CodeTypeItems"]) .... // AggregationLevelConfiguration的其他属性
然後在主視圖中,將SelectList作為附加視圖數據傳遞給EditorTemplate:
@using (Html.BeginForm()) { ... @Html.EditorFor(m => m.Configurations , new { CodeTypeItems = Model.CodeTypeItems }) ... }
方案二:在每次迭代中生成SelectList
將CodeTypeItems
屬性更改為IEnumerable<genericidnametype>
,並將codeTypes
變量設為公共屬性。然後在主視圖中使用以下代碼:
@Html.DropDownListFor(m => m.Configurations[0].HelperCodeType, new SelectList(Model.CodeTypeItems, "Id", "Name", Model.Configurations[0].HelperCodeType))
請注意,使用new { id = "Configurations[0].HelperCodeType" }
是不必要的,因為DropDownListFor()
方法會自動生成id
屬性。
This revised response offers a more concise and clearer explanation of the problem and solutions, while maintaining the original image. The code blocks are also formatted for better readability.
以上是當值在數組中時,如何在mvc5 razor`html.dropdownlistfor`中設置所選值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!