To successfully apply ajax form submission you will have to modify the Register action and the views. By default, in case of error, this action just returns the associated register.aspx view. The first step would be to put the validation summary inside a partial user control:
ValidationSummary.ascx:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%= Html.ValidationSummary("Account creation was unsuccessful. Please correct the errors and try again.") %>
Then you include this partial inside the Register.aspx view:
<div id="validationSummary">
<% Html.RenderPartial("ValidationSummary"); %>
</div>
<% using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "validationSummary" })) { %>
FORM CODE HERE
<% } %>
And finally you modify the Register action:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Register(string userName, string email, string password, string confirmPassword)
{
// ... skipped content for clarity
// If we got this far, something failed, redisplay form
if (Request.IsAjaxRequest())
{
// If an ajax request was made return only the validation errors
// instead of the whole page
return PartialView("ValidationSummary");
}
else
{
return View();
}
}
In case the registration succeeds by default the Register action just redirects to Home/Index. You will have to modify this bit as well, because as you are performing an ajax request the redirection won't work. The same way you could test if you are invoking the action asynchronously and return some text that will indicate that the registration was successful. This text will be displayed inside the same div
as the validation errors.
UPDATE:
One final question - Instead of the
bullet list of error messages, how do
I get each controls error message to
render next to the control using the
Html.ValidationMessage("....") method
?
In order to achieve this you need to put the contents of your form inside a partial view:
<% using (Ajax.BeginForm(
"register",
null,
new AjaxOptions {
HttpMethod = "POST",
UpdateTargetId = "myForm"
},
new {
id = "myForm"
})) { %>
<% Html.RenderPartial("RegisterForm"); %>
<% } %>
And in your register action render the correct partial:
if (Request.IsAjaxRequest())
{
return PartialView("RegisterForm");
}
else
{
return View();
}