I have a simple drop down list, the first item in the list has an empty value. If I do not select anything in the list the client validation ignores it. I have that field set up as required on the model using annotation attributes.
@Html.DropDownListFor(model => Model.CCPayment.State, UnitedStatesStates.StateSelectList)
[Required(ErrorMessage = "State is Required.")]
public string State
{
get
{
return _state;
}
set
{
_state = value;
}
}
any ideas? am I missing something?
It looks like a legitimate bug, here's the best workaround I've found in my search:
http://forums.asp.net/t/1649193.aspx
In short. You wrap the source of the problem,
DropDownListFor
, in a custom Html extension and you manually retrieve the unobtrusive clientside validation rules like this:Then you combine your
validationAttributes
dictionary with any other html attributes passed into your custom helper and you pass that along toDropDownListFor
The complete code that I'm using (I have a label in there too, you can feel free to de-couple):
If the issue is that when you select the 'blank' option, you are not seeing the validation message saying the field is required, it's probably because of how the Html Helper generates the option tag for the 'blank' option. The problem is the empty value attribute.
I used this one-line workaround to remove the value attribute, and it worked like a charm!
$('option[value=""]').removeAttr("value");
All this does is remove the value attribute from any 'option' element with a blank value attribute.
This is the simpliest way I found to do it, just adding
data-val-*-*
attributes inHtmlAttributes
ofDropDownListFor
, inside the view. The following method works with RemoteValidation too, if you do not need remote validation, simply remove the elements containingdata-val-remote-*
:I hope it may help. Best Regards!
You have provided too little information in order for us to be able to pinpoint the problem. You might have forgot to include the proper unobtrusive validation scripts inside your view but who knows? You haven't shown your view.
Here's a full working example:
Model:
Controller:
View:
Notice how we are providing a default value in the
DropDownListFor
helper as last parameter. That will insert an option in the beginning with empty value and custom text and if the user doesn't pick some state the required validator should kick in.I added @class="required" to the attributes like some guy said on the thread at codeplex http://aspnet.codeplex.com/workitem/7629 and it worked fine for me =)