仅更新模型的一部分

Sam*_*ill 2 c# asp.net asp.net-mvc asp.net-mvc-3

我正在使用 ASP.NET MVC 3 和实体框架代码优先。我有一个页面(使用 Razor View Engine),它允许用户更新模型(产品)的一部分:

@Html.LabelFor(model => model.Overview) @Html.TextAreaFor(model => model.Overview)

@Html.LabelFor(model => model.Description)
@Html.TextAreaFor(model => model.Description)

@Html.HiddenFor(model => model.ProductId)
Run Code Online (Sandbox Code Playgroud)

我的控制器方法如下所示:

[HttpPost]
public ActionResult Update(Product product)
{
  db.Products.Attach(product);
  db.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)

我想要做的就是更新产品模型的概述和描述属性。但是,当我运行代码时,模型没有在数据库中更新,我也没有收到任何错误。

当我在调试时检查产品对象时,我发现虽然 ProductId、Overview 和 Description 字段是正确的(根据 FORM POST),但其他字段是 NULL(我期望的)。

我想知道产品对象的不完整状态是否导致它无法保存到数据库?

这是模型:

公共类产品{ public int ProductId { get; 放; }

    [Required(ErrorMessage = "Please enter a description")]
    [DataType(DataType.MultilineText)]
    public string Description { get; set; }

    [DataType(DataType.MultilineText)]
    public string Overview { get; set; }

    public int SupplierId { get; set; }
    public virtual Supplier Supplier { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

har*_*don 5

在编辑时,首先尝试从数据库中选择一条现有记录(您要编辑的记录),然后使用从表单收集的值(即传递给控制器​​操作的模型)更新它,然后保存它。

例如

[HttpPost]
public ActionResult Update(Product productPassedInFromView)
{ 
    Product productToEdit = db.Products.Find(productPassedInFromView.ID);

    productToEdit.Property1 = productPassedInFromView.Property1;
    productToEdit.Property2 = productPassedInFromView.Property2;
    //Continue for all the fields you want to edit.

    db.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)