C# 尝试更新时模型对象不完整
我有以下行动方法:C# 尝试更新时模型对象不完整,c#,asp.net-mvc,asp.net-mvc-3,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.Countrie
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" />
...
public ActionResult ProfileSettings()
{
Context con=新上下文();
ProfileSettingsViewModel model=新的ProfileSettingsViewModel();
model.Cities=con.Cities.ToList();
model.Countries=con.Countries.ToList();
model.UserProfile=con.Users.Find(Membership.GetUser().ProviderUserKey);
返回视图(模型);//此处模型已满,包含所有需要的数据
}
[HttpPost]
公共操作结果概要文件设置(概要文件设置查看模型模型)
{
//通过的模型不好
Context con=新上下文();
con.Entry(model.UserProfile).State=EntityState.Modified;
con.SaveChanges();
返回重定向到操作(“索引”、“主页”);
}
@使用(Html.BeginForm(“ProfileSettings”、“User”、FormMethod.Post、new{id=“submitProfile”}))
{
名字
@Html.TextBoxFor(a=>a.UserProfile.FirstName)
姓
@Html.TextBoxFor(a=>a.UserProfile.LastName)
...
...
当我在POST中点击submit received model时,方法是不完整的。它包含FirstName、LastName等,但UserID为空。因此我无法更新对象。我在这里做错了什么?您应该将UserID存储为表单中的隐藏字段。MVC仅根据请求中的内容重建您的模型。在您的特定情况下,您可以只提交FirstName和LastName,因为这些是视图中包含的唯一调用。MVC模型的行为与视图状态不同,它不存储在任何位置
您也不希望在视图模型中包含整个实体。如果您只需要ID,则应包含ID。然后,您可以从DAL中再次加载实体,更新需要更改的属性,然后保存更改。在视图中添加html标记HiddenFor,并确保您正在填充UserId在您的Get操作中:
@using (Html.BeginForm("ProfileSettings", "User", FormMethod.Post, new { id = "submitProfile" }))
{
@Html.HiddenFor(a => a.UserProfile.UserId)
// your code here..
}