"The Id field is required" validation message on Create; Id not set to [Required]

I ran into this issue with a form in which I was adding "objects" to a list dynamically. Therefore, our users were able to add, remove or update. It all worked well except for the cases when new items were created. For this reason, in my case, excluding the Id property was not an option. The solution was to make the ID Nullable:

public int? Id { get; set; }

This way existing items will have a value and new ones will have null instead. Good stuff.


Great question and answers, saved my ... behind. I need to add something, though:

Instead of

[Bind(Exclude = "Id")]

I think it's better to use

[Bind(Include = "Prop1, Prop2, Prop3, etc")]

.. where Prop1, Prop2 and Prop3 are THE ONLY properties that you want to be bound at the action level.

Since this is white-listing as opposed to black-listing. White-listing is better, safer. This way you also solve the risk of over posting and under posting too. See Brad Wilson's post.


You can add the attribute:

 [Bind(Exclude = "Id")] 

on the parameter in method rather than the class, that way on create you can exclude it and on edit it will still be mandatory:

public ActionResult Create([Bind(Exclude = "Id")] User u)
{
    // will exclude for create
}

public ActionResult Edit(User u)
{
    // will require for edit
}