Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 the result when the optionLabel is left selected.

How do I assign 0 as the value for a DropDownListFor's optionLabel?

EDIT: Here is an example of my DropDownListFor code in my view:

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

When I render the page it creates the list with None at the top like this:

<option value>None</option>

I want it to be like this:

<option value="0">None</option>
like image 796
Chris Stevens Avatar asked Aug 09 '13 18:08

Chris Stevens


2 Answers

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<SelectListItem> InsertEmptyFirst(this IEnumerable<SelectListItem> 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"))
like image 176
heavyd Avatar answered Nov 06 '22 16:11

heavyd


Insert a new empty string, here's an example.

@Html.DropDownListFor(x => x.ProjectID, Model.Projects, string.Empty)
like image 43
Virgilio Fernandes Avatar answered Nov 06 '22 15:11

Virgilio Fernandes