1

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.

abiNerd
  • 1,976
  • 1
  • 18
  • 22

2 Answers2

1

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.

lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228
Sai
  • 391
  • 4
  • 6
  • I don't know why, I've a view which works without this workaround. And I've another view where I had to implement this solution because I was facing this error. – Atiq Baqi Oct 01 '19 at 10:16
0

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.

abiNerd
  • 1,976
  • 1
  • 18
  • 22