C# 避免关系类的模型验证

C# 避免关系类的模型验证,c#,asp.net-mvc-3,C#,Asp.net Mvc 3,我的类的视图类型Usario定义如下 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; s

我的类的视图类型
Usario
定义如下

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; }
}
public分部类Usuario
{
公共用益
{
this.Campana=newhashset();
}
public int IDUsuario{get;set;}
公共int IDPerfil_FK{get;set;}
公共字符串Nombre{get;set;}
公共字符串密码{get;set;}
公共bool Activo{get;set;}
公共虚拟Perfil Perfil{get;set;}
公共虚拟ICollection Campana{get;set;}
}

现在我想知道的是如何避免对视图中与类Usario相关的类campana进行验证,因为当我执行
ModelState.IsValid
时,模型会验证类Usario以及类campana的属性,正确的方法是使用视图模型

您已经有了
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);
}
这样,您只需将所需的数据传递给视图。数据注释对视图模型的工作方式与任何其他类完全相同

模型
由MVC初始化,属性由传入数据通过RouteValue填充,因此您可以执行以下操作:

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

正确的方法是使用视图模型

您已经有了
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);
}
这样,您只需将所需的数据传递给视图。数据注释对视图模型的工作方式与任何其他类完全相同

模型
由MVC初始化,属性由传入数据通过RouteValue填充,因此您可以执行以下操作:

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