MVC2 在 UpdateModel() 中抛出 InvalidOperationException,尝试更新 id 字段
我的 MVC2 应用程序今天让我感到悲伤...我想使用以下控制器代码编辑数据库记录:
[AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "Admin")]
public virtual ActionResult Edit(int id, FormCollection formValues)
{
var masterDataProxy = MasterDataChannelFactory.OpenChannel();
var tester = masterDataProxy.GetTester(id);
masterDataProxy.CloseChannel();
if (null == tester)
{
return View(Views.NotFound);
}
try
{
UpdateModel(tester);
var adminProxy = AdminChannelFactory.OpenChannel();
adminProxy.AddUpdateTester(tester);
adminProxy.CloseChannel();
return RedirectToAction(Actions.Index());
}
catch (Exception ex)
{
ModelState.AddModelError("Tester", ex.Message);
return View(tester);
}
}
我收到高级异常“无法更新类型‘Model.Entity’的模型”,当我深入研究 ModelState 时,我发现尝试更新 Id 字段时失败 - “在实体反序列化期间仅 .NET 3.5+ 支持设置 Id 属性”。
问题是,如何告诉 UpdateModel() 不要更新 Id 字段?我不想让它更新该字段!
有什么想法吗? 戴夫
My MVC2 app is giving me grief today... I want to edit a database record, using the following Controller code:
[AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "Admin")]
public virtual ActionResult Edit(int id, FormCollection formValues)
{
var masterDataProxy = MasterDataChannelFactory.OpenChannel();
var tester = masterDataProxy.GetTester(id);
masterDataProxy.CloseChannel();
if (null == tester)
{
return View(Views.NotFound);
}
try
{
UpdateModel(tester);
var adminProxy = AdminChannelFactory.OpenChannel();
adminProxy.AddUpdateTester(tester);
adminProxy.CloseChannel();
return RedirectToAction(Actions.Index());
}
catch (Exception ex)
{
ModelState.AddModelError("Tester", ex.Message);
return View(tester);
}
}
I'm getting the high-level exception "The model of type 'Model.Entity' could not be updated", and when I drill down into the ModelState I see it's failing when trying to update the Id field -- "Setting the Id property is only supported with .NET 3.5+ during entity deserialization".
The question is, how can I tell UpdateModel() not to update the Id field? I don't want it to update that field!!
Any ideas?
Dave
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试
并确保
Id
不包含在 formValues 中。Try
and make sure
Id
is not included in the formValues.使用
TryUpdateModel(tester)
代替UpdateModel(tester)
Use
TryUpdateModel(tester)
insted ofUpdateModel(tester)