2013-01-22 36 views
6

我有一個簡單的用戶模型編輯窗體,但是當我回發,沒有任何隱藏的輸入值被應用於模型,我不知道爲什麼會發生這種情況。MVC後不向模型添加值

我的剃刀:

@model CMS.Core.Models.UserProfile 

@using (Html.BeginForm()) 
{ 
    @Html.ValidationSummary(true) 

    <fieldset class="normalForm"> 
     <legend>User Profile</legend> 

     @Html.HiddenFor(model => model.UserId) 

     <div class="formRow"> 
      <div class="editor-label"> 
       @Html.LabelFor(model => model.EmailAddress) 
      </div> 
      <div class="editor-field"> 
       @Html.TextBoxFor(model => model.EmailAddress, new { @class = "textbox" }) 
       @Html.ValidationMessageFor(model => model.EmailAddress) 
      </div> 
     </div> 

     <div class="formRow"> 
      <div class="editor-label"> 
       @Html.LabelFor(model => model.FirstName) 
      </div> 
      <div class="editor-field"> 
       @Html.TextBoxFor(model => model.FirstName, new { @class = "textbox" }) 
       @Html.ValidationMessageFor(model => model.FirstName) 
      </div> 
     </div> 

     <div class="buttonRow"><input type="submit" value="Save" class="button" /></div> 
    </fieldset> 
} 

我的控制器:

[HttpPost] 
    public ActionResult Edit(UserProfile user) 
    { 
     if (ModelState.IsValid) 
     { 
      user.Save(); 
      return RedirectToAction("Index"); 
     } 
     return View(user); 
    } 

用戶配置類:

[Table("UserProfile")] 
public class UserProfile 
{ 
    [Key] 
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] 
    public int UserId { get; private set; } 


    [Required(ErrorMessage = "Please enter an email address")] 
    [StringLength(350)] 
    [DataType(DataType.EmailAddress)] 
    [Display(Name = "Email Address")] 
    public string EmailAddress { get; set; } 


    [StringLength(100)] 
    [DataType(DataType.Text)] 
    [Display(Name = "First Name")] 
    public string FirstName { get; set; } 
} 

如果我嘗試user.UserId它返回零(因爲它是一個int),但如果我嘗試Request["UserId"]它返回正確的值,以便正確發佈該值 - 只是沒有添加到UserProfile模型。有誰知道爲什麼發生這種情況還是我能做些什麼來解決它

感謝

+0

如何爲隱藏字段生成html外觀?你也可以發佈你的UserProfile模型嗎? – nemesv

+0

Pete

+1

生成的HTML看起來很好。那麼你可以用你的'UserProfile'類的定義來更新你的文章嗎? – nemesv

回答

7

DefaultModelBinder只能綁定公共屬性

您的屬性setter更改爲公共和它應該很好地工作:

[Key] 
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] 
public int UserId { get; set; } 

如果你不能做到這一點,你需要創建與私營制定者有關係的自定義模型粘合劑。

但作爲一種更好的方法,而不是直接使用您的UserProfile。創建一個UserProfileViewModel,其中UserId是公開的,並在View和Controller操作中使用它。在這種情況下,您需要在您的UserProfileUserProfileViewModel之間進行映射,但是存在諸如AutoMapper之類的好工具。

+0

這就是答案。在這種情況下,不能使用**私人設置**。 –

+0

輝煌,謝謝! – Pete

1

正如@nemesev所說,模型屬性上的訪問器屬性需要爲public

爲了避免爲了讓模型綁定起作用而需要破解數據庫類,您應該真的爲該類創建一個模型,然後您不需要在視圖中使用DTO(它不是不理想)。