asp.net-mvcmodelidentityef-database-firstdatabase-first

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.


Solution

  • 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.