簡體   English   中英

在Razor中設置枚舉下拉列表的默認值

[英]Setting the default value of an enum dropdown in Razor

我正在嘗試創建一個Item編輯屏幕,用戶可以在其中設置Item的屬性ItemType。 理想情況下,當用戶返回屏幕時,下拉菜單將顯示已經與該項目關聯的ItemType。

照原樣,無論item.ItemType是什么,下拉列表都不會在下拉列表中反映出來。 有沒有解決的辦法?

供參考,目前我的代碼是:

<div class="form-group">
      @Html.LabelFor(model => model.ItemType, new { @class = "control-label col-xs-4" })
      <div class="col-xs-8">
           @Html.DropDownListFor(model => model.ItemType, (SelectList)ViewBag.ItemType, new { @class = "form-control" })
           @Html.ValidationMessageFor(model => model.ItemType, String.Empty, new { @class = "text-danger" })
       </div>
</div>

ViewBag設置如下:

var ItemType = Enum.GetValues(typeof(ItemType));
ViewBag.ItemType = new SelectList(ItemType);

如果您使用的是ASP.NET MVC 5,請嘗試僅使用EnumHelper.GetSelectList方法。 然后,您不需要ViewBag.ItemType。

@Html.DropDownListFor(model => model.ItemType, EnumHelper.GetSelectList(typeof(ItemType)), new { @class = "form-control" })

如果不是,則可能需要指定選擇列表的數據值和數據文本字段。

var itemTypes = (from ItemType i in Enum.GetValues(typeof(ItemType))
                 select new SelectListItem { Text = i.ToString(), Value = i.ToString() }).ToList();
ViewBag.ItemType = itemTypes;

然后,因為它是IEnumerable<SelectListItem>您需要更改演員表。

@Html.DropDownListFor(model => model.ItemType, (IEnumerable<SelectListItem>)ViewBag.ItemType, new { @class = "form-control" })

最終,我找到了解決方法-手動創建列表。

<select class="form-control valid" data-val="true" 
    data-val-required="The Item Type field is required." id="ItemType" name="ItemType" 
    aria-required="true" aria-invalid="false" aria-describedby="ItemType-error">
           @foreach(var item in (IEnumerable<SelectListItem>)ViewBag.ItemType)
           {
                <option value="@item.Value" @(item.Selected ? "selected" : "")>@item.Text</option>
           }
 </select>

盡量在View之外和Controller中保留盡可能多的邏輯。

我在自己的回答中看到,似乎您從控制器中選擇了一個枚舉。

我的一個應用程序中有一個DropDownList,其中包含枚舉列表。 它還選擇了一個默認值,但是還為用戶提供了特定的枚舉。 可以從控制器內部設置默認選擇。

該示例基於我的需求,因此您需要適應您的情況。

在控制器中:

public ActionResult Index()
{
    ViewBag.NominationStatuses = GetStatusSelectListForProcessView(status)
}

private SelectList GetStatusSelectListForProcessView(string status)
{
    var statuses = new List<NominationStatus>(); //NominationStatus is Enum

    statuses.Add(NominationStatus.NotQualified);
    statuses.Add(NominationStatus.Sanitized);
    statuses.Add(NominationStatus.Eligible);
    statuses.Add(NominationStatus.Awarded);

    var statusesSelectList = statuses
           .Select(s => new SelectListItem
           {
               Value = s.ToString(),
               Text = s.ToString()
           });

    return new SelectList(statusesSelectList, "Value", "Text", status);
}

在視圖中:

@Html.DropDownList("Status", (SelectList)ViewBag.NominationStatuses)

這種方法將默認項自動設置為在控制器中選擇的枚舉。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM