Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model object incomplete when try 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 hit submit received model in POST method is incomplete. It contains FirstName, LastName etc. But UserID is null. So I can't update object. What am I doing wrong here?

like image 658
1110 Avatar asked Oct 08 '22 12:10

1110


2 Answers

MVC reconstructs your model only based on what's coming in the request. In your particular case, you are only submitting the FirstName and the LastName, because those are the only @Html.TextBoxFor() calls included in your View. MVC models don't behave like ViewState, it isn't stored anywhere.

You also don't want to include your entire Entity in your view-model. If all you need is the ID then that should be all you include. Then you'd load your entity again from your DAL, update the properties that need to be altered, and then save your changes.

like image 196
Pablo Romeo Avatar answered Oct 13 '22 10:10

Pablo Romeo


You should store the UserId as a hidden field in the form.

like image 37
Valamas Avatar answered Oct 13 '22 09:10

Valamas