0

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.

4

1 回答 1

1

为此,您可以将部分视图返回为 html。呈现的部分将包含模型状态错误,因此将在以 html 形式返回时显示。

例子

可以创建一个名为 AjaxResult 的类

public class AjaxResult
{
    public string Html { get; set; }
    public bool Success { get; set; }
}

然后在 ajax 调用的成功函数中,您可以将 html 附加到适当的元素。例如

$.ajax({
    url: 'http://bacon/receive', 
    dataType: "json",
    type: "POST",
    error: function () {
    },
    success: function (data) {
        if (data.Success) {
            $('body').append(data.Html);
        }
    }
});
于 2013-04-03T15:40:58.773 回答