简体   繁体   中英

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. Ideally, when the user returns to the screen, the dropdown would display the ItemType already associated with the Item.

As it is, regardless of what the item.ItemType is, the dropdown will not reflect that in the dropdown. 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:

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. Then you don't need 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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