2

I'm trying to generate a dropdownlist in my view, like the one below except I want my option label ("Please select...") to have a value of -1 as blank is already occupied by another option. Is there anyway to do this without adding it to the select list in my controller or view model, or creating a new html helper?

<%: Html.DropDownListFor(model => model.stuff.Id, new SelectList(Model.stuff, "Id", "Name"), "Please select...")%>

Thanks

2 Answers 2

9

I want my option label ("Please select...") to have a value of -1

You cannot do this out of the box with the DropDownListFor helper. It will always use blank for this value. You have two possibilities:

  1. Write a custom helper
  2. Add it manually to the collection

Actually you have a third possibility which IMHO is the best and what I would recommend you:

Don't use blank as values. This should be reserved for the Please Select default value. It doesn't seem logical to use blank as the value of something that the user can actually select. You might also have problems with the validation.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for confirming what I suspected. This is a one of case so I think I will go with the latter
RE: your last comment, totally with you this one. However this is a particular case and after consideration using blank as a selectable value makes other things a lot simpler.
To expand on option #2, the accepted answer for this post gives a good idea how to implement it: forums.asp.net/t/1572194.aspx/1
1

Just use the Concat method to add a new item to the SelectList after you get your values from the database. Then set the value to 0 and text to "Please Select".

 var selectList = new SelectList(types.Concat( new[]{new MediaType() {MediaTypeId = 0, Type = "Please select"}})
            , "mediatypeid", "type");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.