【发布时间】:2010-01-26 22:01:55
【问题描述】:
当我尝试在 Asp.Net MVC 2 中使用创建样式操作创建实体时,就会发生这种情况。
POCO 具有以下属性:
public int Id {get;set;}
[Required]
public string Message {get; set}
在创建实体时,会自动设置 Id,因此在 Create 操作中不需要它。
ModelState 说“需要 Id 字段”,但我没有这样设置。 这里有自动发生的事情吗?
编辑 - 原因揭晓
Brad Wilson 通过 Paul Speranza 在下面的其中一个 cmets 中回答了问题的原因,他说(为 Paul 喝彩):
您正在为 ID,你只是不知道你是。 它在默认的路由数据中 路线(“{controller}/{action}/{id}”), 其默认值为空 字符串,对 int 无效。 使用您的 [Bind] 属性 用于排除 ID 的操作参数。我的 默认路由是:新 { 控制器 = "客户", action = "编辑", id = " " } // 参数默认值
编辑 - 更新模型技术
实际上,我通过使用 TryUpdateModel 和与之相关的排除参数数组再次改变了执行此操作的方式。
[HttpPost]
public ActionResult Add(Venue collection)
{
Venue venue = new Venue();
if (TryUpdateModel(venue, null, null, new[] { "Id" }))
{
_service.Add(venue);
return RedirectToAction("Index", "Manage");
}
return View(collection);
}
【问题讨论】:
-
您可能会觉得这篇博文很有趣:bradwilson.typepad.com/blog/2010/01/…
-
我确实觉得它很有趣。不能解决这个问题,但可以帮助我想到我将要拥有的其他一些问题
-
如何使“Id”类型安全?像 ()=>id ?
标签: asp.net-mvc asp.net-mvc-2 data-annotations