views:

1213

answers:

1

I create a dropdown list by using ASP.NET MVC helper like this,

<%=Html.DropDownList("Group","-please select a group-")%>

and I get the html like this,

<label for="GroupId">Group:</label>
<select id="GroupId" name="GroupId"><option value="">-please select a group-</option>
<option value="15">Business</option>
<option value="16">Friends</option>
<option value="17">Others</option>
</select>

The default option is "-please selecta group-" and the value is empty.

How can I validate the select value to see if it's empty? I mean if user doesn't choose a group, how can I know it and give user a error message. Now, the code only shows exception error, because the value is empty for the default option.

+1  A: 

The value of Group in the Action will be 0. You could test if Group is zero and call ModelState.AddModelError. It would be better, if it was possible to explicitly set the value of the default item in the dropdownlist, but that is not possible in the Html.DropDownList

Anyway I use the overload:

<%=Html.DropDownList("Group",Model.GroupList ,"-please select a group-")%>

With that you have one Property in the Model for the list of Groups and one for the key of the selected Group. If I use

<%=Html.DropDownList("Group",Model.GroupList ,"-please select a group-")%>

then ModelState.IsValid is always false for me.

Malcolm Frexner
Hi, thank you for your answer. But I could not test if Group is zero. How do u do it?
Smallville
Hi Eric,Model.Group==0 if you use strongly typed view.(int)ViewData["Group"]==0 if you use ViewData as a Dictionary.
Malcolm Frexner