Asp.net-Mvc-3

將字元串數組綁定到 MVC Razor 中的 DropDownList

  • November 2, 2020

你知道我可以很容易地將字元串數組的內容綁定到 MVC Razor 視圖中的 DropDownList 嗎?

public static string[] AgeRagne = new string[] { "Sun", "Mon", "Tues", "Wed" };

更新:下面的程式碼有效。

 @Html.DropDownListFor(
   model => model.Filter.AgeRange,
   new SelectList(Extensions.AgeRange, Model.Filter.AgeRange),
   new { @class = "search-dropdown", name = "ageRange" }
 )

一個不是很好但快速的方法是這樣做:):

<select name="dowList" id="dowList">
   @{string[] AgeRagne = new string[] { "Sun", "Mon", "Tues", "Wed" };}
   @foreach (var dow in AgeRagne)
   {
       <option value="@dow">@dow</option>
   }
</select>

一個 htmlhelper 將是最好的長期穩定的解決方案。

使用您的數組創建一個SelectList並將其傳遞給您的視圖:

SelectList list = new SelectList(AgeRagne);
ViewBag.myList = list;

然後在您看來,使用Html.DropDownlist

@Html.DropDownList("myList", ViewBag.myList as SelectList)

就這樣

引用自:https://stackoverflow.com/questions/10347094