首頁 > 後端開發 > C++ > 當值在數組中時,如何在mvc5 razor`html.dropdownlistfor`中設置所選值?

當值在數組中時,如何在mvc5 razor`html.dropdownlistfor`中設置所選值?

Barbara Streisand
發布: 2025-01-30 00:35:10
原創
726 人瀏覽過

在ASP.NET MVC 5應用程序中,如何使用數組值設置MVC5 Razor Html.DropDownListFor 中的選中值?

How to Set Selected Values in MVC5 Razor `Html.DropDownListFor` When Values are in an Array?

問題描述

在ASP.NET MVC 5應用程序中,目標是使用Configurations數組中的值(特別是AggregationLevelConfiguration.CodeTypeAggregationLevelConfiguration.HelperCodeType字段)來設置CodeTypeItemsHelperCodeTypeItems屬性的選中值。然而,使用new SelectList(codeTypes, "Id", "Name")new SelectList(helperCodeTypes, "Id", "Name")無法設置選中值。

解決方案

方案一:使用EditorTemplate

為名為AggregationLevelConfigurationAggregationLevelConfiguration創建一個自定義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中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板