Asp.net mvc 4 ModelState.IsValid==false,尽管插入了所有模型值
今天我遇到了一个问题,在我将所有数据插入一个公式以创建一个新产品之后,程序会说ModelState.IsValid==false 在调试期间查看modelState时,字段0上出现错误。错误:“CuId字段是必需的” 为了防止我在ProductController.cs中的“创建帖子”操作中正确设置CuId,请执行以下操作:Asp.net mvc 4 ModelState.IsValid==false,尽管插入了所有模型值,asp.net-mvc-4,model,modelstate,Asp.net Mvc 4,Model,Modelstate,今天我遇到了一个问题,在我将所有数据插入一个公式以创建一个新产品之后,程序会说ModelState.IsValid==false 在调试期间查看modelState时,字段0上出现错误。错误:“CuId字段是必需的” 为了防止我在ProductController.cs中的“创建帖子”操作中正确设置CuId,请执行以下操作: [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(Product p
[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>
当我在调试模式下查看模型产品的值时,除了绑定到product.CuId的外键和从数据库自动设置的产品Id之外,所有字段都会被填充(也是CuId)
希望你能帮助我。提前感谢。关于问题的第一部分,在第一次调用方法时,
ModelState
由DefaultModelBinder
填充。如果属性CuId
具有[Required]
属性且其值未回发,则会将错误添加到ModelState
,因此ModelState.IsValid
为false
。仅设置模型的属性不会删除ModelState
值
至于问题的第二部分,您没有在GET方法中将模型传递给视图,因此@Html.HiddenFor(m=>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=>model.CuId,“Customer”)
生成一个Html
,它是一个可访问性元素。单击它将焦点设置为其关联的表单控件。但是您没有关联的表单控件(只是一个无法接收焦点的隐藏输入)
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
}