Hi, I'm using ASP MVC RC1.
A form I'm using contains a dropdownlist which I have put in a view with this code.
<%= Html.DropDownList("areaid", (SelectList)ViewData["AreaId"], "Select Area Id")%>
However, when rendered, this is what I get
<select id="areaid" name="areaid">
<option value="">Select Area Id</option>
<option value="1">Home</option>
...
</select>
What I'd like is for the Select Area Id option to have a value of 0 and mark it as selected by default so it is consistent with the other values and I can validate whether or not an area has been chosen as it is a mandatory value. AreaId is an integer so when I currently click the form without touching the dropdownlist at all, MVC complains that "" is not an integer and gives me a binding error.
SO how do I set a value for the default option and then make it selected on the form?
Thanks, Dan
-
I think you have three options. First when you are building your SelectList or enumerable of SelectItemList, prepend the selection with your option label and default value. Putting it at the top will make it the default if some other value isn't already chosen in the model. Second, you could build the select (and options) "by hand" in the view using a loop to create the options. Again, prepending your default selection if one isn't supplied in the model. Third, use the DropDownList extension, but modify the value of the first option using javascript after the page is loaded.
It doesn't seem to be possible to use the DropDownList extension to assign a value to an optionLabel as it is hard-coded to use
string.Empty
. Below is the relevant code snippet from http://www.codeplex.com/aspnet.// Make optionLabel the first item that gets rendered. if (optionLabel != null) { listItemBuilder.AppendLine(ListItemToOption(new SelectListItem() { Text = optionLabel, Value = String.Empty, Selected = false })); }
Hmobius : Thank you. I now create a Listobject, insert a default option with value 0 at index 0 and pass that to Html.DropDownList. It works a treat. -
Since the drop down represents a mandatory field you can you code the client-side to disable the submission until all mandarory fields have values.
From UI design point of view you shouldn't give the user the option to do something which they in fact cannot do.
Justin : "From UI design point of view", if you don't have a default option then they may overlook the dropdown and end up submitting the form with, for example, a state of Alabama when they're really in Ohio.
0 comments:
Post a Comment