2011-12-02 138 views
1

我查看強類型我這樣定義避免模型驗證

public partial class Usuario 
{ 
    public Usuario() 
    { 
     this.Campana = new HashSet<Campana>(); 
    } 

    public int IDUsuario { get; set; } 
    public int IDPerfil_FK { get; set; } 
    public string Nombre { get; set; } 
    public string Password { get; set; } 
    public bool Activo { get; set; } 

    public virtual Perfil Perfil { get; set; } 
    public virtual ICollection<Campana> Campana { get; set; } 
} 

現在我想知道的是如何避免其與相關類坎帕納的驗證Usario類因爲當我在做ModelState.IsValid該模型驗證班級Usuario和Campana的屬性

回答

1

這樣做的正確方法是使用視圖模型。

您已經有Usuario類,現在您實現了視圖模型,該視圖模型只保存要傳遞給視圖的屬性。喜歡的東西:

public class UsuarioProfileViewModel 
{ 
    public int IDUsuario { get; set; } 
    public string Nombre { get; set; } 
    public bool Activo { get; set; } 

    // Other properties for that view 
} 

現在控制器上:

public ActionResult UsuarioProfile(UsuarioProfileViewModel model) { 
{ 
    // Fill the missing properties for the model (when needed) 

    View(model); 
} 

這種方式,你只傳遞給視圖所需要的數據。數據註釋對視圖模型的工作方式與其他任何類完全相同。

model由MVC初始化和屬性都填補進來的數據,通過routeValues,所以你可以做這樣的事情:

@Html.Action("UsuarioProfile", new { UsuarioID = 10 })