【问题标题】:ModelState.IsValid == false, although all model values are insertedModelState.IsValid == false,尽管插入了所有模型值
【发布时间】:2023-03-29 21:07:01
【问题描述】:

今天我遇到了一个问题,在我将所有数据插入公式以创建新产品后,程序说 ModelState.IsValid==false。

当我在调试期间查看模型状态时,字段 0 出现错误。错误:“需要 CuId 字段”。

为了防止我在 ProductController.cs 中的 Creat POST 操作中正确设置 CuId:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Product product)
    {
        int lastcu = db.Customers.Max(l => l.Id);
        product.CuId = last; 

        if (ModelState.IsValid)
        {
            db.Products.Add(product);
            db.SaveChanges();
            return RedirectToAction("Create", "NewIssue");
        }


        return View(product);
    }

但它再次设置了相同的错误。 我的看法是这样的。实际上 model.CuId 应该已经在那里设置了:

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

<fieldset>
    <legend>Product</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.CuId, "Customer")
        @ViewBag.Cuname    
        @Html.HiddenFor(model => model.CuId, new { id = "lastcu" })
     </div>

我的 GET 控制器如下所示:

 public ActionResult Create()
    {
        int lastcu = db.Cu.Max(l => l.Id);
        //gives the id a Name
        var lastcuname = db.Customers.Find(lastcu).Name;
        //show to User by creating the product
        ViewBag.Cuname = lastcuname;
        ViewBag.CuId = lastcu;

        return View();
    }

当我在调试模式下查看模型产品的值时,除了绑定到 product.CuId 的外键和自动设置的产品 Id 之外,所有字段都被填充(也是 CuId)数据库。

希望你能帮助我。提前致谢。

【问题讨论】:

    标签: asp.net-mvc-4 model modelstate


    【解决方案1】:

    至于您问题的第一部分,ModelState 在首次调用该方法时由 DefaultModelBinder 填充。如果属性CuId 具有[Required] 属性并且其值未回发,则将错误添加到ModelState,因此ModelState.IsValidfalse。仅设置模型的属性不会删除 ModelState 值。

    至于您问题的第二部分,您没有将模型传递给 GET 方法中的视图,因此 @Html.HiddenFor(m =&gt; m.CuId) 会生成一个没有值的隐藏输入(因为 model.CuId 的值是 null 或其默认值)。您当前所做的只是使用您从未使用过的ViewBag(不是好习惯)将一些值传递给视图。相反,将模型传递给视图,如下所示。

    public ActionResult Create()
    {
        int lastcu = db.Cu.Max(l => l.Id);
        var lastcuname = db.Customers.Find(lastcu).Name;
        // Initialize a new instance of the model and set properties
        Product model = new Product()
        {
          CuId = lastcu,
          Cuname = lastcuname // assume this is a property of your model?
        };
        return View(model); // return the model
    }
    

    旁注:@Html.LabelFor(model =&gt; model.CuId, "Customer") 生成一个 html &lt;label&gt;,这是一个可访问性元素。单击它会将焦点设置到其关联的表单控件。但是您没有关联的表单控件(只是一个无法获得焦点的隐藏输入)

    【讨论】:

      猜你喜欢
      • 2021-09-22
      • 1970-01-01
      • 2021-09-14
      • 1970-01-01
      • 1970-01-01
      • 2019-05-20
      • 2016-12-20
      • 2021-02-08
      • 1970-01-01
      相关资源
      最近更新 更多