ModelState.IsValid == false,尽管插入了所有模型值

时间:2015-07-29 09:25:16

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

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

当我在调试期间查看modelState时,字段0上有一个错误。错误:" CuId字段是必需的"。

为了防止我在Product POST动作中将CuId设置为正确,如ProductController.cs中那样:

    [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);
    }

但它又设置了同样的错误。 我的观点看起来像那样。实际上模型.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();
    }

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

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

1 个答案:

答案 0 :(得分:0)

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

至于问题的第二部分,您没有将模型传递给GET方法中的视图,因此@Html.HiddenFor(m => m.CuId)生成一个没有值的隐藏输入(因为model.CuId的值为{{ 1}}或其默认值)。你现在所做的就是使用你从未使用的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 @Html.LabelFor(model => model.CuId, "Customer"),它是一个辅助功能元素。单击它可将焦点设置为其关联的表单控件。但是你没有相关的表单控件(只是一个无法获得焦点的隐藏输入)

相关问题