所以我在将类数据提交到MVC视图时遇到了一些问题。(我刚接触MVC btw)通常情况下,这不会有问题,因为我可以稍后获取数据或执行某些操作,但问题出在我的controller类中,它验证数据返回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
}
这是一个视图:
<table>
@if (ViewBag.Product != null)
{
using (Html.BeginForm("Update", "Product", FormMethod.Post))
{
<tr>
<td>Id</td>
<td>@Html.TextBoxFor(model => model.Id, new { @Value = ViewBag.Product.Id })</td>
<td>@Html.ValidationMessageFor(model => model.Id)</td>
</tr>
<tr>
<td>Code</td>
<td>@Html.TextBoxFor(model => model.Code, new { @Value = ViewBag.Product.Code })</td>
<td>@Html.ValidationMessageFor(model => model.Code)</td>
</tr>
<tr>
<td>Description</td>
<td>@Html.TextBoxFor(model => model.Description, new { @Value = ViewBag.Product.Description })</td>
<td>@Html.ValidationMessageFor(model => model.Description)</td>
</tr>
<tr>
<td>CatalogId</td>
<td>@Html.TextBoxFor(model => model.CatalogId, new { @Value = ViewBag.Product.CatalogId })</td>
<td>@Html.ValidationMessageFor(model => model.CatalogId)</td>
</tr>
<tr>
<td>@Html.ValueFor(model => model.Catalog, new { @Value = ViewBag.Product.Catalog })</td> //<-- This is where my Problem is
<td>@Html.ValidationMessageFor(model => model.Catalog)</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");
}
您需要将目录的属性(可能还有目录id)添加到您的视图中,这可能是一个隐藏字段,以确保它往返返回服务器,并在控制器执行更新时填充到您的模型中。
@Html.HiddenFor(model => model.CatalogId, new { @Value = ViewBag.CatalogId }
@Html.HiddenFor(model => model.Catalog.Id, new { @Value = ViewBag.Catalog.Code }
@Html.HiddenFor(model => model.Catalog.Title, new { @Value = ViewBag.Catalog.Title }
Catalog属性是一个复杂的对象,而MVC本身并不是将其呈现到视图中的方法。在这种情况下,我将需要的属性放入隐藏字段中,以便它们在控制器的编辑/更新操作中可用。