I am trying to make simple DropDownList validation (clear jQuery - no unobtrusive) in my ASP.NET MVC 4 application.
I have fields in model:
[DisplayName("Wybierz płatnika")]
public virtual int? studyPayerId { get; set; }
public virtual IList<StudyPayer> PayersList { get; set; }
Then in controller I do:
var payers = RisDbPersistanceManager.RetrieveEquals<StudyPayer>("IsActive", true);
if (payers != null)
{
model.PayersList = payers; // it is populated
}
model.studyPayerId = null;
And in my View:
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
...
$('#studyPayerId').rules('add',
{
required: true,
messages: {
required: "Proszę wybrać płatnika!"
}
});
...
<div class="formsElement" >
<div class="formsElementLabel" >
@Html.LabelFor(x => x.studyPayerId)
</div>
<div class="formsElementInput" >
@Html.DropDownListFor(x => x.studyPayerId, new SelectList(Model.PayersList, "Id", "Name", Model.studyPayerId), "-- wybierz płatnika --")
@Html.ValidationMessageFor(x => x.studyPayerId)
</div>
</div>
In simple TextBox fields everything works - validates my field on Submit button click. But DropDownList does not display any message when I did not choose anything and leave "-- wybierz płatnika --" selection.
EDIT
<select id="Gender" class="error" name="Gender" style="display: none;">
<label class="error" for="Gender">Proszę wybrać płeć!</label>
<div id="Gender_chosen" class="chosen-container chosen-container-single chosen-container-single-nosearch" style="width: 127px;" title="">
<a class="chosen-single" tabindex="-1">
<span>-- nieokreślona --</span>
<div>
</a>
<div class="chosen-drop" style="top: 34px; bottom: auto;">
</div>