EF 4:仅基于视图中存在的字段更新模型
本文关键字:存在 字段 模型 更新 视图 于视图 EF | 更新日期: 2023-09-27 18:33:36
>假设我有一个模型:
public class HashTable {
public string sKey { get;set; }
public string sValue { get:set; }
}
然后我在视图中呈现它:
<div>Please enter the key/value pair:</div>
@Html.LabelFor(h => h.sKey, "Key");
@Html.TextBoxFor(h => h.sKey);
@Html.LabelFor(h => h.sValue, "Value");
@Html.TextBoxFor(h => h.sValue);
然后我把它保存在控制器中:
db.HashTable.Add(themodel);
然后我在视图中回忆它,但我只想更改值:
<div>Please enter the value:</div>
Key: @Model.sKey
@Html.LabelFor(h => h.sValue, "Value");
@Html.TextBoxFor(h => h.sValue, Model.sValue);
然后我将其提交给控制器。问题是如果我这样做:
db.Entry(oldmodel).CurrentValues.SetValues(themodel);
它将"键"字段清空,因为视图上没有该字段的元素。
这是一个非常简单的示例(代码可能并不完全准确),其中包含一个非常复杂的系统,其中某些表单字段可能会也可能不会根据票证的状态显示在视图中。我真正需要的是一种方法,如果表单字段未显示在视图中,则不会在数据库中更新。有什么想法吗?提前感谢!
在表单中也包含您的密钥。这样,当回发时,它将在模型/视图模型中可用。你可以使用Html.HiddenFor helper方法来实现此目的。
<div>Please enter the value:</div>
Key: @Model.sKey
@Html.LabelFor(h => h.sValue);
@Html.TextBoxFor(h => h.sValue);
@Html.HiddenFor(x=>x.sKey)
编辑:如果您不想在视图中显示如此多的字段,但仍想使用有效的现有数据保存,我将在我的视图中拥有该条目的 ID(例如:ProductId),并使用该 ID 构建现有的产品对象并对其应用新的更改并保存回来。 像这样的事情
<div>Please enter the value:</div>
Key: @Model.sKey
@Html.LabelFor(h => h.ProductPrice);
@Html.TextBoxFor(h => ProductPrice);
@Html.HiddenFor(x=>x.ProductId)
操作方法将如下所示
[HttpPost]
public ActionResult Edit (ProductViewModel newModel)
{
var oldProduct=repositary.GetProduct(newModel.ProductID);
oldProduct.ProductPrice=newModel.ProductPrice;
//Now save the oldProdcut
}
<</div>
div class="answers"> 首先,您需要将主键呈现为隐藏元素。
<div>Please enter the value:</div>
Key: @Model.sKey
@Html.HiddenFor(h => h.sKey)
@Html.LabelFor(h => h.sValue);
@Html.TextBoxFor(h => h.sValue);
然后在控制器的"编辑"操作中使用 UpdateModel()
方法。此帮助程序函数将值从窗体集合复制到模型。无需确定哪些字段是可编辑的,因为UpdateModel
会为您执行此操作。
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection formValues)
{
HashTable hash = repository.GetHashTable(id);
UpdateModel(hash);
repository.Save();
return RedirectToAction("Details", new { id = hash.DinnerID });
}