views:

68

answers:

2

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

+1  A: 

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

[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.

DSO
Thanks, I knew I had to be forgetting something. However, it is throwing the following exception: The model of type 'MyProject.User' was not successfully updated. What could be causing this?
qui
You need to get error details. See this link: http://stackoverflow.com/questions/1092806/mvc-models-not-successfully-updated-but-cant-find-reason
DSO
A: 

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);
qui