3

這是我在這裏舉一個例子結合:http://aspalliance.com/1776_ASPNET_MVC_Beta_Released.5排除在模特屬性使用接口

public ActionResult Save(int id) 
{ 
Person person = GetPersonFromDatabase(id); 
try 
{ 
    UpdateMode<IPersonFormBindable>(person) 
    SavePersonToDatabase(person); 

    return RedirectToAction("Browse"); 
} 
catch 
{ 
    return View(person) 
} 
} 

interface IPersonFormBindable 
{ 
string Name {get; set;} 
int Age {get; set;} 
string Email {get; set;} 
} 

public class Person : IBindable 
{ 
public string Name {get; set;} 
public int Age {get; set;} 
public string Email {get; set;} 
public Decimal? Salary {get; set;} 
} 

這不會值映射到財產收入,而且將執行其驗證屬性,當你這樣做的標準預計不會[綁定(不包括= 「工資」)

[Bind(Exclude="Salary")] 
public class Person 
{ 
public string Name {get; set;} 
public int Age {get; set;} 
public stiring Email {get; set;} 
public Decimal? Salary {get; set;} 
} 

將如何使用這個接口模式我實現[綁定(不包括= 「房產」)

+0

問題在哪裏? :) – Lorenzo 2010-12-16 01:08:31

+0

嗨,我認爲這個問題已經很明顯。這是你的問題。 – 2010-12-16 02:00:01

回答

2

下面是我會推薦你​​的:使用視圖模型,並刪除這些接口,不要混淆你的控制器這麼多的代碼。所以,你不需要薪水在這一特定的行動受約束:偉大的,使用特別定製的視圖模型這一觀點:

public class PersonViewModel 
{ 
    public string Id { get; set; } 
    public string Name { get; set; } 
    public int Age { get; set; } 
    public string Email { get; set; } 
} 

而且你的控制器動作:

public ActionResult Save(PersonViewModel person) 
{ 
    _repository.SavePersonToDatabase(person); 
    return RedirectToAction("Browse"); 

    // Notice how I've explicitly dropped the try/catch, 
    // you weren't doing anything meaningful with the exception anyways. 
    // I would simply leave the exception propagate. If there's 
    // a problem with the database it would be better to redirect 
    // the user to a 500.htm page telling him that something went wrong. 
} 

如果另一您需要薪水的行動,然後編寫特定於此視圖的另一個視圖模型。如果在視圖模型之間重複一些屬性,請不要擔心。這正是他們的意思。很明顯,您的存儲庫可以使用模型而不是查看模型。所以你需要在這兩種類型之間進行映射。我建議你使用AutoMapper來達到這個目的。

這是我的觀點:總是編寫專門針對特定視圖需求量身定製的視圖模型。儘量避免包含,排除或有一天它會咬你,有人將添加一些敏感的財產,並會忘記將其添加到排除列表。即使你使用Include,它仍然很難看。

+0

你在哪裏放置驗證?在視圖模型或域模型上? – 2010-12-19 22:26:04

+1

@geocine,在視圖模型上,這是控制器從視圖接收到的內容,這代表了用戶輸入,這是應該執行第一級驗證的地方。簡單的驗證,如所需的屬性,日期時間格式,......數據存儲中用戶是否已存在等業務驗證應在服務級別執行,這是第二級驗證。這是業務規則驗證的地方。 – 2010-12-19 22:30:14