2012-06-18 27 views
5

我有以下操作方法:模型對象不完整時,嘗試更新

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方法是不完整的。它包含名字,姓氏等,但UserID爲空。所以我無法更新對象。我在這裏做錯了什麼?

回答

2

MVC僅基於請求中的內容重建您的模型。在您的特定情況下,您只提交名字和姓氏,因爲這些是您視圖中包含的唯一@Html.TextBoxFor()調用。 MVC模型的行爲不像ViewState,它不存儲在任何地方。

你也不想在你的視圖模型中包含你的整個實體。如果你所需要的只是身份證,那麼這應該是你所包含的一切。然後,您將再次從您的DAL加載實體,更新需要更改的屬性,然後保存更改。

+0

+1很好的答案。 –

1

您應該將UserId作爲隱藏字段存儲在表單中。

1

添加HTML標記HiddenFor在您看來,並確保你在你的獲取動作填入用戶名:

@using (Html.BeginForm("ProfileSettings", "User", FormMethod.Post, new { id = "submitProfile" })) 
     { 

@Html.HiddenFor(a => a.UserProfile.UserId) 
// your code here.. 

} 
相關問題