【问题标题】:how to show multiple validation messages in view of MVC5如何根据 MVC5 显示多个验证消息
【发布时间】:2016-10-26 03:44:33
【问题描述】:

我的视图有一个文本框(电子邮件)和一个提交按钮。

@using (Html.BeginForm("FindMyDetail", "ResetPassword", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
   {
      @Html.AntiForgeryToken()
      <h4>Enter your email.</h4>

     @Html.ValidationSummary(false, "", new { @class = "alert alert-danger" })

 @Html.ValidationMessageFor(m=>m.Email)
<div class="form-group">
    @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @*@Html.TextBoxFor(m => m.Email, new { @class = "form-control", @value = @Html.DisplayFor(m => m.Email) })*@
        @Html.TextBoxFor(m => m.Email, true, htmlAttributes: new { @class = "form-control", placeholder = "Enter Email Id you used to register" })
    </div>
</div>
<div class="form-group">
    <div class="col-md-offset-2 col-md-10">

        <input type="submit" class="btn btn-default" value="Email Link" />

    </div>
</div>

}

我必须在 MVC Web 应用程序的视图中显示多个验证消息。

案例1:当文本框为空时显示验证消息以输入电子邮件ID。

Case2:如果电子邮件存在,则提交按钮触发邮件。如果邮件失败(false),则应该出现电子邮件不存在的验证消息。 单击提交按钮后,控制器会触发将邮件发送到给定电子邮件的控制器。如果成功,我将返回带有成功消息的不同视图,否则我将返回相同的视图(EmailLink 视图)

在 asp.net webforms 中实现这似乎很容易,但看起来非常不同,我很困惑如何在 MVC 中实现它,因为我是新手。

编辑:我需要使用自定义验证来实现它。不使用数据注释。

【问题讨论】:

  • 这听起来很基础,所有内容都应该包含在 Visual Studio 附带的 mvc 项目模板中
  • 我需要模型的自定义验证消息。
  • ModelState.AddModelError?

标签: c# asp.net asp.net-mvc asp.net-mvc-5 asp.net-validators


【解决方案1】:

有两种简单的方法可以做到这一点,您可以在客户端或服务器端进行验证。

客户端

在您的页面中导入此 jquery 插件: http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.min.js

在您的 javascript 文件上,您可以创建所需的验证,例如:

$(document).ready(function() {
  $("#FindMyDetail").validate({
    rules: {
      Email: {
        required: true,
        maxlength: 40,
        email: true
      }
    },
    messages: {
      Email: {
        required: "We need your email address to contact you",
        email: "Your email address must be in the format of name@domain.com"
      }
    }
  });
});

服务器端

您可以使用 asp.net 框架并让它验证您的模型。你必须用一些属性来装饰你的模型,比如:

public class Person
{
    public int ID { get; set; }

    [Required]
    [StringLength(40)]
    public string Email { get; set; }
}

在你的控制器的动作中:

[HttpPost]
public ActionResult Create(Person person)
{
    if (ModelState.IsValid)
    {
        //foo
        return RedirectToAction("Index");
    }

    return View(person);
}

【讨论】:

  • 我需要它是自定义验证消息。
  • 刚刚编辑了我的答案以在验证中显示自定义消息。
猜你喜欢
  • 2021-08-29
  • 2013-04-03
  • 2016-10-31
  • 1970-01-01
  • 1970-01-01
  • 2016-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多