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?
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.
You should store the UserId as a hidden field in the form.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With