MVC 4: How to make DropDownListFor return 0 as the value of the Label option?

I have a creation view with several DropDownListFors. Every time a new object is created, only 1 of the DropDownListFors should have a value, I want the rest to return 0 as the result when choosing the Label option.

How to set 0 as the value for DropDownList for the Label option?

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

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

When I create the page, it creates a list with None at the top, like this:

 <option value>None</option> 

I want it to be like this:

 <option value="0">None</option> 
+4
source share
2 answers

The documentation for DropDownFor optionLabel parameter (where you pass "None") as:

The text for the empty item by default.

Thus, it will always be an empty element. You will need to add an additional item to your selection list to get a value of 0.

I used the following extension method to accomplish this (sorry unchecked, 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 as follows:

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

Insert a new blank line, here is an example.

 @Html.DropDownListFor(x => x.ProjectID, Model.Projects, string.Empty) 
+1
source

Source: https://habr.com/ru/post/1496217/


All Articles