数据注释检查唯一字段

时间:2015-05-27 14:12:35

标签: entity-framework asp.net-mvc-4 razor data-annotations

我试图检查注册系统的数据库中是否已存在用户名。但实施此功能后,我的注册系统无效,如果用户名存在,他不会告诉我!

型号:

    public class RegisterModel
{
    [Required]
    [Remote("IsUserExist", "Account", ErrorMessage = "User already exist!")]
    [Display(Name = "Nom d'utilisateur")]
    public string UserName { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "La chaîne {0} doit comporter au moins {2} caractères.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Mot de passe")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirmer le mot de passe ")]
    [Compare("Password", ErrorMessage = "Le mot de passe et le mot de passe de confirmation ne correspondent pas.")]
    public string ConfirmPassword { get; set; }

    [Required]
    [DataType(DataType.EmailAddress, ErrorMessage = "E-mail is not valid")]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [Display(Name = "Prénom")]
    public string Fname { get; set; }

    [Required]
    [Display(Name = "Nom")]
    public string Lname { get; set; }
}

IsUserExist

    public JsonResult IsUserExist(string username)
    {
        var exist = WebSecurity.UserExists(username);
        return Json(!exist, JsonRequestBehavior.AllowGet);
    }

我的观点:

@model Projet2.Models.RegisterModel
@{
ViewBag.Title = "S'inscrire";
}

<hgroup class="title">
<h1>@ViewBag.Title.</h1>
<h2>Créez un nouveau compte.</h2>
</hgroup>

@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary()

<fieldset>
    <legend>Formulaire d'inscription</legend>
    <ol>
        <li>
            @Html.LabelFor(m => m.UserName)
            @Html.TextBoxFor(m => m.UserName)
        </li>
        <li>
            @Html.LabelFor(m => m.Password)
            @Html.PasswordFor(m => m.Password)
        </li>
        <li>
            @Html.LabelFor(m => m.ConfirmPassword)
            @Html.PasswordFor(m => m.ConfirmPassword)
        </li>
        <li>
            @Html.LabelFor(m => m.Email)
            @Html.TextBoxFor(m => m.Email)
        </li>
        <li>
            @Html.LabelFor(m => m.Lname)
            @Html.TextBoxFor(m => m.Lname)
        </li>
        <li>
            @Html.LabelFor(m => m.Fname)
            @Html.TextBoxFor(m => m.Fname)
        </li>
    </ol>
    <input type="submit" value="S'inscrire" />
</fieldset>
}

@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("~/Scripts/jquery-1.8.2.min.js")
@Scripts.Render("~/Scripts/jquery.validate.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.js")
@Scripts.Render("~/Scripts/buttonset.js")
@Scripts.Render("~/Scripts/input-control.js")
}

我的代码中是否有错误或我必须做其他事情?

先谢谢!

PokeRstarrr

0 个答案:

没有答案