Invalid model object when trying to update

I have the following action methods:

public ActionResult ProfileSettings()
        {
            Context con = new Context();
            ProfileSettingsViewModel model = new ProfileSettingsViewModel();
            model.Cities = con.Cities.ToList();
            model.Countries = con.Countries.ToList();
            model.UserProfile = con.Users.Find(Membership.GetUser().ProviderUserKey);
            return View(model); // Here model is full with all needed data
        }

        [HttpPost]
        public ActionResult ProfileSettings(ProfileSettingsViewModel model)
        {
            // Passed model is not good
            Context con = new Context();

            con.Entry(model.UserProfile).State = EntityState.Modified;
            con.SaveChanges();

            return RedirectToAction("Index", "Home");
        }

@using (Html.BeginForm("ProfileSettings", "User", FormMethod.Post, new { id = "submitProfile" }))
        {
            <li>
                <label>
                    First Name</label>
                @Html.TextBoxFor(a => a.UserProfile.FirstName)
            </li>
            <li>
                <label>
                    Last Name</label>
                @Html.TextBoxFor(a => a.UserProfile.LastName)
            </li>
...
<input type="submit" value="Save" />
...

When I find that the resulting received model in the POST method is incomplete. It contains FirstName, LastName, etc. But UserID is NULL. Therefore, I cannot update the object. What am I doing wrong here?

+5
source share
3 answers

MVC reconstructs your model only based on what is included in the request. In your particular case, you only send FirstName and LastName, because these are the only @Html.TextBoxFor()calls included in your view. MVC models do not behave like ViewStatethey are not stored anywhere.

Entity . , , , . DAL, , , .

+2

UserId .

+1

Add the HiddenFor html tag to your look and make sure you populate the UserId in the Get action:

@using (Html.BeginForm("ProfileSettings", "User", FormMethod.Post, new { id = "submitProfile" }))
        {

@Html.HiddenFor(a => a.UserProfile.UserId)
// your code here..

}
+1
source

All Articles