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

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

Mary-Kate Olsen
Mary-Kate Olsen原創
2025-01-30 00:26:09565瀏覽

How to Set the Selected Item in an MVC5 Razor @Html.DropDownListFor when the Value is in an Array?

在MVC5 Razor中,當@Html.DropDownListFor的值為數組時,如何設置選定項?

ASP.NET MVC中的@Html.DropDownListFor 輔助方法用於為模型中的屬性生成下拉列表。當模型屬性為數組或集合時,將為數組或集合中的每個項目呈現下拉列表。

然而,當值在數組或集合中時,設置下拉列表的選中值可能會很棘手。默認情況下,選中值將基於數組或集合中的第一項設置。

要設置值在數組或集合中的選中值,您可以使用以下兩種方法:

方法一:使用編輯器模板

為集合中的類型創建一個自定義編輯器模板。在Views/Shared/EditorTemplates/AggregationLevelConfiguration.cshtml中創建一個部分視圖,包含以下代碼:

<code class="language-csharp">@model yourAssembly.AggregationLevelConfiguration
@Html.DropDownListFor(m => m.HelperCodeType, (SelectList)ViewData["CodeTypeItems"])
.... // AggregationLevelConfiguration的其他属性</code>

然後在主視圖中,將SelectList作為附加ViewData傳遞給編輯器模板:

<code class="language-csharp">@using (Html.BeginForm())
{
  ...
  @Html.EditorFor(m => m.Configurations , new { CodeTypeItems = Model.CodeTypeItems })
  ...
}</code>

方法二:在每次迭代中生成新的SelectList並設置選中值

在此方法中,將CodeTypeItems屬性設為IEnumerable<genericidnametype>而不是SelectList。然後在主視圖中,為Configurations數組中的每個項目生成一個新的SelectList

<code class="language-csharp">@Html.DropDownListFor(m => m.Configurations[0].HelperCodeType, new SelectList(Model.CodeTypeItems, "Id", "Name", Model.Configurations[0].HelperCodeType))</code>

請注意,此方法僅適用於Configurations數組的第一個元素。 對於數組中的其他元素,需要進行循環處理並為每個元素分別生成SelectList。 這可能需要使用循環結構(如for循環或foreach循環)來迭代數組,並在每次迭代中生成並渲染一個新的DropDownListFor。 這將確保每個下拉列表都正確地設置其選中值。

以上是當值在數組中時,如何在mvc5 razor @html.dropdownlistfor中設置所選項目?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn