MVC3远程验证 [英] MVC3 Remote Validation

查看:145
本文介绍了MVC3远程验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在设置使用MVC3,这样,如果他们所选择的用户名已经存在的提醒用户远程验证的proccess。一切都建立和APPART从最重要的部分工作正常,没有显示错误消息。如果我提交显示为页面错误消息的形式被刷新的有关模型状态错误添加。

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.

反正是有刷新了JSON结果模型验证总结?

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

推荐答案

样品code:

Web.config文件必须包含这样的:

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

这是在控制器

[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:

这篇关于MVC3远程验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆