111*_*110 5 c# asp.net-mvc asp.net-mvc-3
我有以下行动方法:
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" />
...
Run Code Online (Sandbox Code Playgroud)
当我点击提交收到的模型在POST方法是不完整的.它包含FirstName,LastName等.但UserID为null.所以我无法更新对象.我在这做错了什么?
MVC 仅根据请求中的内容重建您的模型。在您的特定情况下,您只需提交名字和姓氏,因为这些是@Html.TextBoxFor()您的视图中包含的唯一调用。MVC 模型的行为不像ViewState,它不存储在任何地方。
您也不希望将整个实体包含在视图模型中。如果您只需要 ID,那么您应该只包含 ID。然后,您需要从 DAL 再次加载实体,更新需要更改的属性,然后保存更改。
| 归档时间: |
|
| 查看次数: |
218 次 |
| 最近记录: |