我有以下操作方法:
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" />
...
当我在 POST 方法中点击提交时收到的模型不完整。它包含 FirstName、LastName 等。但 UserID 为空。所以我不能更新对象。我在这里做错了什么?