【发布时间】: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