简体   繁体   中英

jQuery Validation in MVC3 Project

When I create a new MVC3 application, add a model, add a [Required] attribute to the model, scaffold a new edit view for this model, and add a @Html.ValidationMessageFor(...) , everything works beautifully. If I attempt to submit the edit form without filling in a value it gives me a validation message.

My problem is that this is not working in the enterprise app I'm working on. Here's what I've done and I wonder if you can think of anything else I can check to troubleshoot. I can't share the code, but perhaps you can see an obvious omission from the list...

  • Add [Required] attribute to my model's property
  • Make sure jquery.validate.js and jquery.validate.unobtrusive.js are referenced
  • Added Html.EnableClientValidation(true) and Html.EnableUnobtrusiveJavaScript(true) on my view
  • Added my @Html.ValidationMessageFor(...) next to my control (which is a @Html.TextBoxFor )

The issue is that I can submit the form and no validation is performed. I get a server-side error stating that the entity is not valid, which I would expect if it gets past the client-side validation.

When I inspect the source, it has not rendered the validation attributes to my textbox. I would expect it to look something like this...

<input class="text-box single-line" data-val="true" 
    data-val-required="The Property1 field is required." 
    id="Property1" name="Property1" type="text" value="" />

But instead it looks more like this...

<input id="Reminder_Description" name="Reminder.Description" 
    style="width:300px;" type="text" value="" />

What exactly is responsible for injecting those attributes?

Thanks!

I figured out the issue. I just didn't know that attributes are not passed through a service layer (WCF), so the Required attribute was not effective. To remedy, we added a local reference to the entities assembly (which makes sense in our architecture). Thanks.

Have you checked your web.config for:

<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM