ValidationMessage To get the error message

I have a partial view:

 @Html.EditorFor(model => model.BM)
 @Html.ValidationMessageFor(model => model.BM)

      

In the main view, if I do this:

@using (Html.BeginForm())
{
   @Html.Partial("QuoteStep1", Model)
}

      

Then call $ ('form'). validate () validates the form and an error is displayed if I don't fill in the details.

However, if instead I load the partial view using an AJAX call and then calling $ ('form'). validate () still works (it returns true or false correctly), but the error message is no longer displayed!

I read somewhere that I should add the following to the top of my Partial View:

@if (this.ViewContext.FormContext == null) 
{
   this.ViewContext.FormContext = new FormContext(); 
 }

      

But this has no effect.

[EDIT: UPDATE ON MY RESEARCH]

After more than two hours of debugging, I learned a few things. First, since I am loading the form content with an AJAX request, the newly added HTML controls are not part of the DOM. So there is no way to validate jquery about these controls.

So adding the following line of code to the AJAX success callback SHOULD do the trick:

$.validator.unobtrusive.parse($('form'));

      

This is set right after adding the AJAX result to the DOM.

When I debug further in the validator, I see that the code being called is:

 $(selector).find(":input[data-val=true]").each(function () {
            $jQval.unobtrusive.parseElement(this, true);
        });

      

Meaning, he found a newly added input field.

The $ jQval.unobtrusive.parseElement method uses the following code:

 this.adapt({
                    element: element,
                    form: form,
                    message: message,
                    params: paramValues,
                    rules: rules,
                    messages: messages
                }); 

      

and the element is my textbox, the form is the submission form, and the message is "BM must be a number". So everything looks good to me.

But guess what ... The validation error message still doesn't show up!

Any jquery guru to help please? :)

+3
jquery jquery-validate asp.net-mvc asp.net-mvc-4 unobtrusive-validation


source to share


No one has answered this question yet

Check out similar questions:

2268
Why is my JavaScript code getting the error "No Access-Control-Allow-Origin header" on the requested resource ", but not Postman?
70
unobtrusive validation does not work with dynamic content
nine
asp.net mvc 3 jquery add validation message manually
6
Client check not showing message
3
Editing an input field when Html.ValidationMessageFor displays an error
2
ASP.NET MVC 3 unobtrusive client side validation with dynamic content
2
Client side validation not working with ASP.Net MVC Razor and Ajax form
2
use jquery validation plugin on mvc form page
1
Jquery validation: remove error message from form
0
JQuery validation remains valid after ajax postback



All Articles
Loading...
X
Show
Funny
Dev
Pics