简体   繁体   中英

Id is not posted in ASP.NET MVC

When I post my model, the Id is missing :

I have an NHibernate database model "Contact" :

       public class Contact : Entity<int>
        {
            public virtual string LastName { get; set; }
            public virtual string FirstName { get; set; }
        }

        public abstract class Entity<TId>
        {
            public virtual TId Id { get; protected set; }

            public override bool Equals(object obj)
            {
                return Equals(obj as Entity<TId>);
            }
        }

I

n the controller, I set the model:

    public class MyModel
    {
        public Contact Contact { get; set; }
    }

public ActionResult MyController()
{
    MyModel model = new MyModel();

    model.Contact = ... //come from DB

    return PartialView("Contact", model);
}

In the view, I do this :

@Html.HiddenFor(m => m.Contact.Id) (when I replace with a TextBoxFor, I see the correct value)

When I post the form, in the controller all the value are in the model but the Contact.Id is 0 all the time

I post like this :

var jqxhr = $.post("Controller/MyAction", $("form").serialize(),
    function (data) {
    });

In the controller :

[HttpPost]
public ActionResult MyAction(MyModel model)
{
    //model.Contact.Id equal 0 all the time
    //other value (fields) are ok.
}

Any idea ?

Thanks,

You need a public setter for the id property:

public virtual TId Id { get; set; }

Otherwise how do you expect the default model binder being able to set its value? Oh, and by the way that's one of the 10^10 + 1 reasons why you should use view models in your views instead of your domain objects.

So here's how a more realistic MyModel would look like:

public class MyViewModel
{
    public string Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

That's what you should pass to a view and that's what you should get in return. The rest is mapping between this view model and your actual domain objects. This mapping could be greatly simplified with tools like AutoMapper . This way you leave your domain as is and you tailor the view models according to the specific requirements of the given views they are designed for.

Your Id is private set . That's why the model binder can't set the value. You should change it to a public setter:

public virtual TId Id { get; set; }

Protected set on identity.

MVC does the following:

  1. new Object()
  2. Set values from form.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM