简体   繁体   English

在Razor中设置枚举下拉列表的默认值

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

I'm trying to create an Item edit screen where the user can set a property of the Item, the ItemType. 我正在尝试创建一个Item编辑屏幕,用户可以在其中设置Item的属性ItemType。 Ideally, when the user returns to the screen, the dropdown would display the ItemType already associated with the Item. 理想情况下,当用户返回屏幕时,下拉菜单将显示已经与该项目关联的ItemType。

As it is, regardless of what the item.ItemType is, the dropdown will not reflect that in the dropdown. 照原样,无论item.ItemType是什么,下拉列表都不会在下拉列表中反映出来。 Is there a way around this? 有没有解决的办法?

For reference, my code at the moment is: 供参考,目前我的代码是:

<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>

The ViewBag is set with the following: ViewBag设置如下:

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

If you're using ASP.NET MVC 5, try just using the EnumHelper.GetSelectList method. 如果您使用的是ASP.NET MVC 5,请尝试仅使用EnumHelper.GetSelectList方法。 Then you don't need ViewBag.ItemType. 然后,您不需要ViewBag.ItemType。

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

If not, you might need to specify the data value and data text fields of the select list. 如果不是,则可能需要指定选择列表的数据值和数据文本字段。

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

Then since it's an IEnumerable<SelectListItem> you'll need to change your cast. 然后,因为它是IEnumerable<SelectListItem>您需要更改演员表。

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

Eventually I found a fix - manual creation of the list. 最终,我找到了解决方法-手动创建列表。

<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>

Try to keep as much of the logic outside of the View and in the Controller. 尽量在View之外和Controller中保留尽可能多的逻辑。

I saw in your self answer that it looks like you have an enum selected from wihin your controller. 我在自己的回答中看到,似乎您从控制器中选择了一个枚举。

I have a DropDownList in one of my apps that contains a list of Enums. 我的一个应用程序中有一个DropDownList,其中包含枚举列表。 It also has a default value selected, but also has specific enums available to the user. 它还选择了一个默认值,但是还为用户提供了特定的枚举。 The default selection can be set from within the controller. 可以从控制器内部设置默认选择。

This example is based on what my needs were, so you'll need to adapt to your case. 该示例基于我的需求,因此您需要适应您的情况。

In the controller: 在控制器中:

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);
}

In the view: 在视图中:

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

This approach will automatically set the default item to the enum that was selected in the controller. 这种方法将默认项自动设置为在控制器中选择的枚举。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM