views:

355

answers:

3

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?

Thank you

A: 

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.

Craig Stuntz
@Craig (1) It can't be nullble since it's my pk for Entity. (2) I'm submitting it from my form with 0 (zero) value. (3) Use another type isn't an option. And you are right, why it solves the error when I change name form Id to PK ? Regards
Zote
You say you're submitting it, but the error message says you're not. That, plus the fact that it works when you rename it, probably means you got the name wrong. Check the form data with Fiddler or Firebug to be sure.
Craig Stuntz
A: 

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.

Thank you I tried your way, but for my project I got a "cleaner" option. See my answer here.
Zote
A: 

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.

Zote