自定义 属性 的验证消息

ValidationMessage for custom property

我正在尝试制作一个具有 asp.net 身份的主页。我真的希望我的用户有一个自定义的显示名称,而不是将他们的电子邮件用作 "Welcome, foo@bar.com".

我需要帮助来验证显示名称,该名称在 html 中显示一条消息,该名称已经存在,但我不知道该怎么做。

到目前为止,我的代码有效,如果您选择的显示不存在,您将获得它,但如果不存在,它将 return 到同一页面,这是预期的。但是没有消息告诉你显示名称已经存在,我只有 [Length(14)].

的验证器

告诉我应该如何继续告诉我的用户显示已被占用。

    public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
    {
        if (User.Identity.IsAuthenticated)
        {
            return RedirectToAction("Index", "Manage");
        }

        DAL.ProjectStrawberryEntities ctx = new DAL.ProjectStrawberryEntities();

        Regex regex = new Regex(@"^[a-zA-Z0-9]*$");
        Match match = regex.Match(model.DisplayName);

        bool displayNameExist = ctx.AspNetUsers.Any(a => a.Displayname == match.Value);

        if (ModelState.IsValid && !displayNameExist)
        {
            // Get the information about the user from the external login provider
            var info = await AuthenticationManager.GetExternalLoginInfoAsync();
            if (info == null)
            {
                return View("ExternalLoginFailure");
            }
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email, DisplayName = model.DisplayName };
            var result = await UserManager.CreateAsync(user);
            if (result.Succeeded)
            {
                result = await UserManager.AddLoginAsync(user.Id, info.Login);
                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
                    return RedirectToLocal(returnUrl);
                }
            }
            AddErrors(result);
        }

        ViewBag.ReturnUrl = returnUrl;
        return View(model);
    }

<div class="form-group">
    @Html.LabelFor(m => m.DisplayName, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.TextBoxFor(m => m.DisplayName, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.DisplayName, "", new { @class = "text-danger" })
    </div>
</div>

使用可以使用您控制器的 ModelStateDictionary.AddModelError to add an error for a property. An instance of this class that will be used by your view, is ModelState 属性。

比如在你的action方法中,你可以这样写

ModelState.AddModelError("DisplayName", "DisplayName already exists.");

然后 return 当前视图而不是重定向。

return View();

所以代码可能是这样的:

if (ModelState.IsValid && !displayNameExist)
{   
     //Save 
     //return RedirectToAction(your action)
     //return Redirect(your redirect url)
}
else
{
     ModelState.AddModelError("DisplayName", "DisplayName already exists.");
     //If you need add something to ViewBag you can do it here
     return View();
}