MVC 4: How to make DropDownListFor return 0 as optionLabel value?

前端 未结 2 1707
长发绾君心
长发绾君心 2021-01-13 07:09

I have a create view with multiple DropDownListFors. Each time a new object is created only 1 of the DropDownListFors should have a value, I want the others to return 0 as t

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-13 07:31

    In the documentation for DropDownFor the optionLabel parameter (where you're passing "None") is described as:

    The text for a default empty item.

    So this is designed to always be an empty item. You will need to add an additional item into your select list in order to get a 0 value.

    I have used the following extension method to accomplish this (sorry untested, there may be minor errors):

    public IEnumerable InsertEmptyFirst(this IEnumerable list, string emptyText = "", string emptyValue = "")
    {
        return new [] { new SelectListItem { Text = emptyText, Value = emptyValue } }.Concat(list);
    }
    

    You would use it like this:

    @Html.DropDownListFor(model => model.cardReward.ID, new SelectList(ViewBag.cardReward, "Id","Name").InsertEmptyFirst("None", "0"))
    

提交回复
热议问题