2012年3月31日星期六

ERROR: The ID field is required.

ERROR: The ID field is required.



问题

      昨天晚上在家里试着使用Asp.net MVC 4,并学习使用AreaRe girstration, 创建了一个新的Area叫做“Admin”,运行正常。而遇到的问题是实现步骤如下:

  1. 添加新model类,叫SiteColumn
  2. 在Area/Admin/Controllers下添加针对SiteColumn的Controller,同时支持Index , Create, Edit, Update及Delete
  3. 进入 Create 准备进行添加操作
  4. 输入完整的数据提交

     在这里面我会遇到错误,但界面没有什么变化及提示(实际上有,但没有文字)。

 

      之后,通过修改Create.cshtml中,将@Html.ValidationSummary(true)改成 @Html.ValidationSummary("Error Messages:");终于出现了错误信息如下:

Error Messages:

  • The ID field is required.

解决方案

修改处理POST的Create方法:

修改前:

[HttpPost]
public ActionResult Create(SiteColumn sitecolumn)

修改后:

[HttpPost]
public ActionResult Create([Bind(Exclude="id")]SiteColumn sitecolumn)


原因

             http://stackoverflow.com/questions/2142990/asp-mvc-the-id-field-is-required-validation-message-on-create-id-not-set-to

摘下其中一段:

The reason for the issue is answered by Brad Wilson via Paul Speranza in one of the comments below where he says (cheers Paul):

You're providing a value for ID, you just didn't know you were. It's in the route data of the default route ("{controller}/{action}/{id}"), and its default value is the empty string, which isn't valid for an int. Use the [Bind] attribute on your action parameter to exclude ID. My default route was: new { controller = "Customer", action = "Edit", id = " " } // Parameter defaults

不过,有个奇怪且暂时不解的是,网站的默认Controller及View下按默认创建步骤,没加[Bind(Exclude = “ID”)] 仍然可以提交并成功添加数据。 有谁知道的可以说明一下,谢谢!



TAG: