1

我目前正在使用 MVC3 设置远程验证,以便在用户选择的用户名已经存在时收到警报。从最重要的部分开始,一切都已设置并正常工作,没有显示错误消息。如果我提交表单,则会在页面刷新并添加相关模型状态错误时显示错误消息。

无论如何用 Json 结果刷新模型验证摘要?

4

1 回答 1

1

示例代码:

Web.config 必须包含以下内容:

    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />

视图是这样的:

@model Dommer.Domain.RegisterModel
@{
    ViewBag.Title = "Create";
}

<h2>Create New User</h2>

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true, "Account creation was unsuccessful. Please correct the errors and try again.")
    <div>
        <fieldset>
            <legend>Account Information</legend>

            <div class="editor-label">
                @Html.LabelFor(m => m.UserName)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.UserName)
                @Html.ValidationMessageFor(m => m.UserName)
            </div>

            <div class="editor-label">
                @Html.LabelFor(m => m.Email)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.Email)
                @Html.ValidationMessageFor(m => m.Email)
            </div>

            <div class="editor-label">
                @Html.LabelFor(m => m.Password)
            </div>
            <div class="editor-field">
                @Html.PasswordFor(m => m.Password)
                @Html.ValidationMessageFor(m => m.Password)
            </div>

            <div class="editor-label">
                @Html.LabelFor(m => m.ConfirmPassword)
            </div>
            <div class="editor-field">
                @Html.PasswordFor(m => m.ConfirmPassword)
                @Html.ValidationMessageFor(m => m.ConfirmPassword)
            </div>
        </fieldset>
        <input type="submit" value="Create User" />
    </div>
}

这是传递给视图的模型:

public class RegisterModel
{
    [Required]
    [RegularExpression(@"(\S)+", ErrorMessage = "Username cannot contain spaces.")]
    [Remote("CheckUserName", HttpMethod="POST")]
    [Display(Name = "Username")]
    public string UserName { get; set; }

    [Required]
    [Remote("CheckEmailAddress", ErrorMessage="{0} already has an account, please enter a different email address.", HttpMethod="POST")]
    [DataAnnotationsExtensions.Email(ErrorMessage="{0} is not a valid email address.")]
    [Display(Name = "Email address")]
    public string Email { get; set; }

    [Required]
    [ValidatePasswordLength]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}

这是在控制器中

[HttpPost]
public JsonResult CheckUserName(string userName, Guid? userId = null)
{
    if (userName != null || userName.Length > 2)
    {
        var users = Membership.FindUsersByName(userName);
        if (users.Count == 0)
        {
                return Json(true);
        }
        else
        {
            if ((users[userName].ProviderUserKey as Guid?) == userId)
            {
                return Json(true);
            }
            else
            {
                string suggestedUID = String.Format(CultureInfo.InvariantCulture, "{0} is not available.", userName);
                for (int i = 1; i < 100; i++)
                {
                    string altCandidate = userName + i.ToString();
                    if (Membership.FindUsersByName(altCandidate).Count == 0)
                    {
                        suggestedUID = String.Format(CultureInfo.InvariantCulture, "{0} is not available. Try {1}.", userName, altCandidate);
                        break;
                    }
                }
                return Json(suggestedUID);
            }
        }
    }
    else
    {
        return Json(true);
    }
}

这将尝试在名称上附加数字,直到找到可用的用户名,并且会在不进行完整回发的情况下执行以下操作:

在此处输入图像描述

于 2012-01-20T17:10:29.047 回答