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


source to share





All Articles