MVC3远程验证

发布于 2024-12-28 06:13:47 字数 148 浏览 0 评论 0原文

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

是否有办法用 Json 结果刷新模型验证摘要?

I am currently in the proccess of setting up remote validation using MVC3 so that a user is alerted if their chosen username already exists. Everything is set up and working correctly appart from the most important part, the error message not being displayed. If I submit the form the error message is displayed as the the page is refreshed with the relevant model state error added.

Is there anyway to refresh the model validation summary with a Json result?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

沫雨熙 2025-01-04 06:13:47

示例代码:

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);
    }
}

这将尝试将数字附加到名称,直到找到可用的用户名并执行类似的操作这无需进行完整的回发:

在此处输入图像描述

Sample code:

Web.config must contain this:

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

The view is like this:

@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>
}

This is the model being passed to the View:

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; }
}

This is in the controller

[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);
    }
}

This will try appending numbers to the name until it finds an available username and will do something like this without doing a full postback:

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文