ASP.NET MVC AJAX with HTML.ValidationMessageFor

2020-06-16 05:46发布

问题:

I'm used to the ASP.NET Webforms easy way of doing AJAX with UpdatePanels. I understand the process is much more artisanal with MVC.

In a specific case, I'm using Data Annotations to validate some form inputs. I use the HTML.ValidationMessageFor helper to show an error message. If I want to use AJAX to post this form and show this error message, what would be the process? Is it possible to keep the HTML.ValidationMessageFor and make it work with AJAX?

Thank you.

回答1:

This article might be helpful: ScottGu's blog: ASP.NET MVC 2: Model Validation.

The validation used in MVC can be both client and server side. To enable client-side validation use the:

 <% Html.EnableClientValidation(); %>

declaration somewhere in your view. This negates the need to use AJAX to post your form to the server and then display the results inline, as users with javascript enabled will have their own clientside validation.



回答2:

Are you using the built-in AJAX methods? For example, are you created the AJAX form with Ajax.BeginForm(...)? If so, it's very easy to show validation messages.

One more thing: do you want to display a validation message for each individual incorrect control, or do you just want to have a validation summary above your form? I'm pretty sure you're asking about displaying an individual message for each control, but I'll include both just in case.


To display an individual message for each incorrect control:

First, you need to put your form inputs inside a Partial View. I'll call that Partial View RegisterForm.ascx.

Next, you should have something like this in your view:

<% using (Ajax.BeginForm("MyAction", null, 
    new AjaxOptions { 
        HttpMethod = "POST", 
        UpdateTargetId = "myForm" 
    }, 
    new { 
        id = "myForm" 
    })) { %>

     <% Html.RenderPartial("RegisterForm"); %>

<% } %>

Finally, your Controller Action should look something like this:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyAction(CustomViewModel m)
{
    if(!m.IsValid) //data validation failed
    {
        if (Request.IsAjaxRequest()) //was this request an AJAX request?
        {
            return PartialView("RegisterForm"); //if it was AJAX, we only return RegisterForm.ascx.
        }
        else
        {
            return View();
        }
    }
}

To display only a validation summary above your form:

You should first create a separate ValidationSummary Partial View. Here's what the code of ValidationSummary.ascx should look like:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%= Html.ValidationSummary("Form submission was unsuccessful. Please correct the errors and try again.") %>

Next, inside your view, you should have something like this:

<div id="validationSummary">
    <% Html.RenderPartial("ValidationSummary"); %>
</div>

<% using (Ajax.BeginForm("MyAction", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "validationSummary" })) { %>
    <!-- code for form inputs goes here -->
<% } %>

Finally, your Controller Action should resemble this:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyAction(CustomViewModel m)
{
    if(!m.IsValid) //data validation failed
    {
        if (Request.IsAjaxRequest()) //was this request an AJAX request?
        {
            return PartialView("ValidationSummary"); //if it was AJAX, we only return the validation errors.
        }
        else
        {
            return View();
        }
    }
}

Hope that helps!