Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

You have a required field, Id. It's required because it's non-nullable. You must either (1) submit it with your form or (2) change your model to make Id nullable or (3) use a different type.

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

Could anyone give an elaborate explanation for this alleged "bug"?

Maybe someone from the Microsoft MVC Team could give an explanation?

There are no bugs like this when using the ADO.NET Entity Data Model as a data source - only on Linq To SQL.

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

I experienced the exact same issue.

One other reason can be:

If you declare your key as some type other than a number e.g String, then since by default it can't auto generate the keys for you, you'll face this error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top