2017-04-03 140 views
0

我有一個包裝我的實體的視圖odel。它看起來像這樣:嵌套實體的綁定屬性

public class EmailTemplateViewModel 
{ 
    public List<EmailAccount> EmailAccounts { get; set; } 
    public EmailTemplate EmailTemplate { get; set; } 

    [Display(Name = "Email Account")] 
    public int EmailAccountId { get; set; } 

} 

,我要保存在回發實體是EmailTemplateEmailAccount嵌套在EmailTemplate之內,但我使用這種視圖模型,所以我可以構建一個下拉列表以供用戶選擇(因爲它不相關,我刪除了該代碼)。

在我的控制器,以獲取電子郵件模板,我喜歡這種結合:

public ActionResult Edit([Bind(Include = "EmailAccountId, EmailTemplate")] EmailTemplateViewModel emailTemplateViewModel) 
{ 

} 

通過defualt這個結合的EmailTenplate每個屬性。如果我不希望有問題的視圖能夠插入某些屬性,有沒有辦法指定嵌套模板上的某些屬性進行綁定?

我想:

public ActionResult Edit([Bind(Include = "EmailAccountId, EmailTemplate.Property1, EmailTemplate.Property2")] EmailTemplateViewModel emailTemplateViewModel) 
{ 

} 

但這不到風度的工作。有沒有這樣做的MVC功能,或者我必須顯式添加屬性到視圖模型,然後將它們映射到控制器中的嵌套實體?

回答

0

你可以嘗試這樣的事:

[Bind(Exclude="EmailAccounts")] 
public class EmailTemplateViewModel 
{ 
    public List<EmailAccount> EmailAccounts { get; set; } 
    public EmailTemplate EmailTemplate { get; set; } 
    [Display(Name = "Email Account")] 
    public int EmailAccountId { get; set; } 
} 

[Bind(Exclude="Property1,Property2")] 
public class EmailTemplate 
{ 
    public string Property1 {get;set;} 
    public string Property2 {get;set;} 
    public string Property3 {get;set;} 
}