ASP.NET MVC模型/ ViewModel验证

blu*_*blu 5 validation asp.net-mvc viewmodel data-annotations

我在Linq-to-Sql中有模型类,其中部分类标有数据注释属性和对xVal的引用.

当我将视图直接绑定到模型时,一切都很好,xVal生成的JS和服务器端双重检查.

我的许多视图都没有输入到一个特定的模型,所以我正在设置视图模型类.我没有公开整个模型实例,而是将属性暴露给我允许/需要由视图设置的模型.

// foo model 
public class Foo {
    public string FooField { ... }
    public Bar Bar { ... }
}

// bar model, where bar is a parent relationship of foo in the db
public class Bar {
    public string BarField { ... }
}

// view model stuff
public class FooViewModel {
    private Foo foo;

    public FooViewModel() {
        foo = new Foo() { Bar = new Bar() };
    }

    public Foo Model {
        get { return foo; }
        set { foo = value; }
    }

    public string BarField { 
        get { return foo.Bar.BarField; }
        set { foo.Bar.BarField = value; }
    }

    public string ExtraViewModelField {
        get; set; 
    }
}
Run Code Online (Sandbox Code Playgroud)

此方法正确填充视图模型类,并且存储库可以正确填充记录.

但它根本没有通过验证.我查看了发出的客户端代码,验证数组对于xval是空的.此外,IsValid的服务器端检查始终为true.

我是否可以通过视图模型的属性来获取数据注释以进行验证,或者我应该以另一种方式执行此操作?

Jam*_*s S 0

您可以发布您的 xval 帮助程序代码和一些 Html.Helpers 吗?

它需要实体和前缀,所以我不明白为什么视图模型中的结构应该有任何区别。就像是:

<%= Html.ClientSideValidation<Foo>("Foo") %>
<%= Html.ClientSideValidation<Bar>("Foo.Bar") %>
Run Code Online (Sandbox Code Playgroud)

詹姆士