【发布时间】:2021-07-03 09:52:21
【问题描述】:
所以我在将类数据出价到 ASP.NET MVC 视图时遇到了一些问题(顺便说一句,我是 ASP.NET MVC 的新手)。
通常这不会有问题,因为我可以稍后获取数据或执行某些操作,但问题出在我的控制器类中,它验证数据返回 false 并破坏函数。
我可以删除验证器,但不幸的是它是必需的,我没有时间重写它。
我离题了...我的问题是如何在视图上绑定数据并将其正确发送到控制器?
这是模型类:
public partial class Product
{
public int Id { get; set; }
public string Code { get; set; }
public string Description { get; set; }
public int CatalogId { get; set; }
public virtual Catalog Catalog { get; set; } //<-- This is where my Problem is
}
这是模型-视图绑定的控制器方法:
public ActionResult Update(int? id)
{
if(id != null)
{
var productManager = new ProductManager();
var model = productManager.GetProductByID(id.Value);
return View(model);
}
return RedirectToAction("Index");
}
这是视图:
@if (Model != null)
{
using (Html.BeginForm("Update", "Product", FormMethod.Post))
{
<tr>
<td>Id</td>
<td>@Html.TextBoxFor(model => model.Id, new { @Value = Model.Id })</td>
<td>@Html.ValidationMessageFor(model => model.Id)</td>
</tr>
<tr>
<td>Code</td>
<td>@Html.TextBoxFor(model => model.Code, new { @Value = Model.Code })</td>
<td>@Html.ValidationMessageFor(model => model.Code)</td>
</tr>
<tr>
<td>Description</td>
<td>@Html.TextBoxFor(model => model.Description, new { @Value = Model.Description })</td>
<td>@Html.ValidationMessageFor(model => model.Description)</td>
</tr>
<tr>
<td>@Html.HiddenFor(model => model.CatalogId, new { @Value = Model.CatalogId })</td>
<td>@Html.HiddenFor(model => model.Catalog, new { @Value = Model.Catalog })</td>
<td>@Html.HiddenFor(model => model.Catalog.Id, new { @Value = Model.Catalog.Id })</td>
<td>@Html.HiddenFor(model => model.Catalog.Code, new { @Value = Model.Catalog.Code })</td>
<td>@Html.HiddenFor(model => model.Catalog.Description, new { @Value = Model.Catalog.Description })</td>
<td>@Html.HiddenFor(model => model.Catalog.Product, new { @Value = Model.Catalog.Product })</td>
</tr>
<tr>
<td><button type="submit">Update</button></td>
</tr>
}
}
这是更新产品的控制器方法:
[HttpPost]
[ActionName("Update")]
public ActionResult Update(EURIS.Entities.Product product)
{
if (ModelState.IsValid) //<-- Product.Catalog is null and IsValid return false
{
ProductManager productManager = new ProductManager();
productManager.UpdateProduct(product);
}
return RedirectToAction("Index");
}
【问题讨论】:
标签: c# asp.net-mvc entity-framework .net-core entity-framework-core