abiNerd
abiNerd

Reputation: 2043

MVC ModelState error "The ID field is required" although the database generates an ID

I created the MVC application database-first with the ID field being generated by the database.

Since the ID is generated by the database, in the Model I set the 'StoreGeneratedPattern' property to 'Identity'.

However, I am still getting the ModelState error "The ID field is required" when I submit a 'create' form.

I have tried restarting the solution, cleaning it, re-building it. I know that I have had this problem before, so if I figure it out I will post the answer here so that future me can find it.

Upvotes: 1

Views: 3119

Answers (2)

Sai
Sai

Reputation: 391

For the edit view, you need to have the id in order to update the appropriate row.

If you remove @Html.HiddenFor(model => model.ID) => System will always generate new row whenever you try to edit the form.

You can follow the below code in order to reuse the same view for both create/Edit

if (model != null)

{

    @Html.HiddenFor(model => model.ID)
}

=> When you try to create a form - model will be null initially so the hidden field will not be executed.

=> When you try to edit hidden field stores your id.

Upvotes: 1

abiNerd
abiNerd

Reputation: 2043

I had included an @Html.HiddenFor(model => model.ID) on the 'create' view.

So although the application would have gladly accepted no ID, it didn't want to accept null as the ID.

I just removed the @Html.HiddenFor and it worked.

P.S. The 'edit' view needs the @Html.HiddenFor(model => model.ID) to remember what the ID was.

Upvotes: 0

Related Questions