简体   繁体   中英

ASP.NET MVC posted entity not mapping to LINQ model

I have a page which is strongly typed to my "User" class. When it is loaded, I load it by Id from the database and pass it to the view.

When the edit form is posted, the object gets posted to the controller method fine, with some other parameters. The object has its properties filled from the form, but it's ID (which obviously isnt on the form) doesnt get posted.

Even when I manually set it to an ID in code and try and save my context, nothing happens on the database.

Here is a rough view of the code with stuff taken out for brevity.

public ActionResult MyProfile()
{
    ViewData["Countries"] = new SelectList(userService.GetCountries(), "id", "name");
    return View(userService.GetById(CurrentUser.id));
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyProfile(MSD_AIDS_Images_Data.LINQRepositories.User user, string password2)
{
    user.id = CurrentUser.id;  //user id isn't posted, so need to reassign it
userService.SaveChanges();
}

I have written code like this a dozen times and it has worked, what is going wrong?

EDIT

When I debug the user object, it's PropertyChanged and PropertyChanging properties are set to NULL

The User object coming into the MyProfile method is not associated with a LINQ context. You need to use explicit binding using UpdateModel , eg:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyProfile(int id, string password2)
{
    MSD_AIDS_Images_Data.LINQRepositories.User user = <LINQ query to load user by id>;

    UpdateModel(user); // updates the model with form values

    userService.SaveChanges();
}

Note you can implement a custom model binder that does this before calling your controller method so you can accept User as a parameter, but I'm assuming you haven't done this.

I fixed the Model binding issues by using an Update Model overload which allows you to specifiy which properties in the model you wish to update:

    string[] includeProperties = {"password", "firstname", "lastname", "email", "affiliation", "countryId"};
    UpdateModel(user, includeProperties);

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