【问题标题】:Error message position in mvc razormvc razor 中的错误消息位置
【发布时间】:2014-07-01 15:45:04
【问题描述】:

我正在尝试为登录和注册表单添加自定义错误消息。

到目前为止,我有一个表单来检查是否有一个电子邮件已经注册,如果是,它会返回

Response.Write("There's already someone with that email")

但是这样做的问题是消息只会出现在网站的顶部。

有没有办法可以在其他地方显示这些错误消息?

我知道我可以在模型中放入

[Required(ErrorMessage = "Something here")]

然后把视图放在某个地方

@Html.ValidationMessageFor(a =>a.Email)

它会在那里显示错误。

我现在的代码是这样的:

[HttpPost]
    public ActionResult Register(Registration signingUp)
    {


        var db = new ShareRideDBEntities();

        if (ModelState.IsValid)
        {
            //find if email is already signed up
            var FindEmail = db.tblProfiles.FirstOrDefault(e => e.PROF_Email == signingUp.Email);
            //if email is not found up do this
            if (FindEmail == null)
            {
                var Data = db.tblProfiles.Create();
                Data.PROF_Password = signingUp.Password;
                Data.PROF_Email = signingUp.Email;
                db.tblProfiles.Add(Data);

                int Saved = db.SaveChanges();

                if (Saved != 0)
                {
                    Response.Write("Registration Successful.");
                }

                else
                {
                    Response.Write("There was an error.");
                }

            }
            else
            {
                Response.Write("There's already an user with that email.");
                return View();
            }
        }
        else
        {
            Response.Write("Fill all the fields to continue.");
        }

return View();

现在,如果我对现有电子邮件执行此操作,它将返回“已有用户使用该电子邮件”。但它会显示在网站顶部。

如何让这个错误信息显示在其他地方?

我听说过@Html.Raw(),但我对如何使用它感到困惑。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 razor


    【解决方案1】:

    使用this.ModelState.AddModelError 方法,您可以添加任何您想要的自定义错误消息。如果您将属性名称指定为键 - 它将由相应的ValidationMessageFor 显示。所以在控制器中而不是直接写响应:

    ModelState.AddModelError("Email", "There's already an user with that email.");
    return View();
    

    并查看您已经拥有的这条线:

    @Html.ValidationMessageFor(a =>a.Email)
    

    将在您放置它的页面的任何部分显示此消息(可能靠近电子邮件字段)。

    【讨论】:

    • 感谢您的快速回答,也很简单,谢谢!
    猜你喜欢
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多