Reputation: 143
How to load ValidationSummary using ajax? I was trying to use MVC's ready Membership.
Simple question, but I'm stuck.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
[RecaptchaControlMvc.CaptchaValidator]
public ActionResult Register(RegisterModel model, bool captchaValid, string captchaErrorMessage)
{
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
if (captchaValid)
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");
}
ModelState.AddModelError("", captchaErrorMessage);
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
View:
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<fieldset>
<legend>Registration Form</legend>
<ol>
<li>
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName)
@Html.ValidationMessageFor(m => m.UserName)
<input type="hidden" id ="some" value=""/>
</li>etc.
I don't want to redirect each time on for example, if username exists or etc.
Upvotes: 0
Views: 1756
Reputation: 15609
To do this you can return a partial view as html. The rendered partial will contain the modelstate errors and therefore will display when returned as html.
Example
Could can create a class called AjaxResult
public class AjaxResult
{
public string Html { get; set; }
public bool Success { get; set; }
}
Then in your success function from the ajax call you can append the html to the appropriate element. e.g.
$.ajax({
url: 'http://bacon/receive',
dataType: "json",
type: "POST",
error: function () {
},
success: function (data) {
if (data.Success) {
$('body').append(data.Html);
}
}
});
Upvotes: 1