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!