【问题标题】:why my validation is not working? asp.net mvc为什么我的验证不起作用? asp.net mvc
【发布时间】:2021-05-20 11:19:02
【问题描述】:

我尝试在我的视图中添加ValidationMessageFor 来控制数据,但它不起作用,数据进入我的发布操作。

这是我的模型类:

 public enum CustomerType
    {
        JuridicalPerson,
        NaturalPerson
    }
    public class Customer
    {
        [Key]
        [DisplayName("ID")]
        public int CustomerId { get; set; }
        [Required(ErrorMessage = "Please enter your first name")]
        [DisplayName("First name")]
        [DataType(DataType.Text)]
        public string FirstName { get; set; }
        [Required(ErrorMessage ="Please enter your last name")]
        [DisplayName("Last name")]
        [DataType(DataType.Text)]
        public string LastName { get; set; }
        [Required(ErrorMessage ="Please choose your customer type")]
        [DisplayName("Customer type")]
        public CustomerType CustomerType { get; set; }

这是我的创建客户视图:

@model Contracts.Models.Customer

@using (Html.BeginForm())
{
    <div class="box">
        <div class="input-container">
            @Html.LabelFor(model => model.FirstName)
            <br />
            @Html.EditorFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>
        <div class="input-container">
            @Html.LabelFor(model => model.LastName)
            <br />
            @Html.EditorFor(model => model.LastName)
            @Html.ValidationMessageFor(model => model.LastName)
        </div>
        <div class="input-container">
            @Html.LabelFor(model => model.CustomerType)
            <br />
            @Html.EnumDropDownListFor(model => model.CustomerType, "Select a type", new {@class ="input-container" })
            @Html.ValidationMessageFor(model => model.CustomerType)
        </div>
        <input class="btn" type="submit" value="Create" />
    </div>
}

最后这是我的客户控制器及其创建客户的操作:

 [HttpPost]
        public ActionResult Create(Customer customer)
        {
//db is my database context
            db.Customers.Add(customer);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

实际上,在我看来,使用 html 助手验证,空输入应该会给出错误,而不是执行我的操作,但不起作用

如果你能帮助我,我将不胜感激

【问题讨论】:

  • 您是否在使用客户端验证脚本,例如不显眼的 jquery?它是通过布局页面或其他方式注入到您的视图中吗?
  • 对不起,我是初学者。不,我没有使用任何脚本,除了我在布局页面中添加的一个 scripts.render 用于在我的视图中添加 css。我该怎么办?

标签: c# asp.net-mvc validation model-view-controller


【解决方案1】:

尝试使用

if (ModelState.IsValid){
        db.Customers.Add(customer);
        db.SaveChanges();
        return RedirectToAction("Index");} return Page();

【讨论】:

  • 谢谢你,它有效。感谢您的帮助。
猜你喜欢
  • 2018-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-15
  • 1970-01-01
  • 2017-07-03
  • 2020-08-14
  • 2020-06-30
相关资源
最近更新 更多