Reputation: 26940
I have this code in my view:
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"type="text/javascript"></script>
...
<div class="modal_label">
@Html.LabelFor(model => model.Organization.Type)
</div>
<div class="modal_field">
@Html.DropDownListFor(model => model.Organization.Type, (IEnumerable<SelectListItem>)ViewBag.TypeList, String.Empty)
@Html.ValidationMessageFor(model => model.Organization.Type)
</div>
If I change @Html.DropDownFor to @Html.EditorFor, then validation is working, but in this case I have following html rendered:
<select id="Organization_Type" name="Organization.Type" class="valid">
...
</select>
Here is my model:
[MetadataType(typeof(OrganizationMetaData))]
public partial class Organization
{
}
public class OrganizationMetaData
{
[Required(ErrorMessageResourceType = typeof(CCMESResources.ResourceErrors),ErrorMessageResourceName = "ValueIsRequired")]
public int Type { get; set; }
}
When the form posts, there ARE errors in ModelState. Can you help me?
Upvotes: 1
Views: 3706
Reputation: 360
In your model (or view model), when you assign a value to it from a drop down list, if the first selected value is an empty string or null, it "should" trigger validatation, but it will take a trip to the server to do it. I've been unsuccessful in getting unobtrusive validation to work client side without doing a post first. Using a nullable field for a required value generally is not a good idea. Also, because you're not using a nullable field, it should force validation when you check to see if the model is valid. Here's a snippet from my project which works (also, I'm using the data annotation extensions for the "Min" annotation):
Model:
[Display(Name = "Ticket Priority")]
[Min(1, ErrorMessage = "You must select a ticket priority.")]
public int TicketPriorityID { get; set; }
View:
<div class="editor-label">
@Html.LabelFor(model => model.TicketPriorityID)
</div>
<div class="editor-field">
@Html.DropDownList("TicketPriorityID", string.Empty)
@Html.ValidationMessageFor(model => model.TicketPriorityID)
</div>
Controller (HttpGet):
ViewBag.TicketPriorityID = new SelectList(db.TicketPriorities.OrderBy(x => x.TicketPriorityID).ToList(), "TicketPriorityID", "Name");
Controller (HttpPost):
if (ModelState.IsValid)
{
...
}
Upvotes: 1
Reputation: 1038830
Make sure that you have used a nullable type on your view model:
[Required]
public int? Type { get; set; }
In your model you seem to have used a non-nullable integer which is not coherent with what you are trying to achieve on your view.
Also make sure that the controller action that you are POSTing this form to takes the view model as action parameter.
Upvotes: 3