ASP.MVC 2 RTM + ModelState Identifier Error

I have the following classes:

public class GroupMetadata { [HiddenInput(DisplayValue = false)] public int Id { get; set; } [Required] public string Name { get; set; } } [MetadataType(typeof(GrupoMetadata))] public partial class Group { public virtual int Id { get; set; } public virtual string Name { get; set; } } 

And this action:

 [HttpPost] public ActionResult Edit(Group group) { if (ModelState.IsValid) { // Logic to save return RedirectToAction("Index"); } return View(group); } 

What is my opinion:

 <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Group>" %> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <% using (Html.BeginForm()) {%> <fieldset> <%= Html.EditorForModel() %> <p> <input type="submit" value="Save" /> </p> </fieldset> <% } %> <div> <%=Html.ActionLink("Back", "Index") %> </div> </asp:Content> 

But ModelState is always invalid! As I can see, for checking MVC 0 is not valid, but really for me. How can I fix this since I did not apply any validation in the Id property?

UPDATE: I don’t know how and why, but renaming Id, in my case to PK, solves this problem.

Do you know that this is a problem in my logic / configuration, or is an error or expected behavior?

+7
asp.net-mvc-2 modelstate asp.net-mvc-2-validation
source share
5 answers

Just before if (ModelState.IsValid) remove the Id index with this line ModelState.Remove("Id") so that when the MVC command removes this error, you just need to remove this code from your project line.

+9
source share

You have a required field, Id . This is necessary because it is not null. You must either (1) send it with your form, or (2) change your model to make Id with a zero value or (3) use a different type.

+1
source share

I can confirm that removing the id index using ModelState.Remove("Id") works.

Can someone give a detailed explanation of this alleged "mistake"?

Perhaps someone from the Microsoft MVC team can give an explanation?

There are no such errors when using the ADO.NET Entity Data Model as a data source - only for Linq To SQL.

+1
source share

Your problem is that you are using a property called 'id' in your model. Try using a different name and you will see that it works. Mvc seems to have a problem with this.

I experienced the same problem.

0
source share

Another reason could be:

If you declare your key as some type other than a number, for example String , then, by default, it cannot automatically generate keys for you, you will encounter this error.

0
source share

All Articles