Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.MVC 2 RTM + ModelState Error at Id property

I have this 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);
}

That's my view:

<%@ 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 MVC validation 0 is invalid, but for me is valid. How can I fix it since, I didn't put any kind of validation in Id property?

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

Do you know if this an issue in my logic/configuration or is an bug or expected behavior?

like image 642
Zote Avatar asked Mar 31 '10 18:03

Zote


1 Answers

Just before if (ModelState.IsValid) remove Id index using this line ModelState.Remove("Id") this way when MVC team remove this bug, you just need to remove this line code of your projects.

like image 170
Zote Avatar answered Nov 03 '22 21:11

Zote