2012-06-18 9 views
5

を更新するには、私は次のアクションメソッドがあります:私は、POSTメソッドで受け取ったモデルが不完全であるsubmitをクリックするとモデルオブジェクト試みが

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" /> 
... 

を。 FirstName、LastNameなどが含まれますが、UserIDはnullです。だから私はオブジェクトを更新することはできません。私はここで間違って何をしていますか?

答えて

2

MVCは、リクエストに含まれるものに基づいてモデルを再構築します。あなたの特定のケースでは、FirstNameとLastNameは、あなたのビューに含まれている唯一の@Html.TextBoxFor()コールであるため、送信しています。 MVCモデルはViewStateのように振る舞いません。どこにも格納されません。

ビューモデルにエンティティ全体を含めたくない場合もあります。あなたが必要とするのはIDだけです。次に、DALからエンティティを再度読み込み、変更が必要なプロパティを更新して、変更を保存します。

+0

1良い答えを。 –

1

ユーザーIDをフォームに非表示フィールドとして格納する必要があります。

1

は、HTMLのタグを追加HiddenForあなたのビューで、あなたはあなたのGETアクションでユーザーIDを移入していることを確認してください。

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

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

} 
関連する問題