ASP.NET MVC模型/视图模型验证 [英] ASP.NET MVC Model/ViewModel Validation
问题描述
我在LINQ到SQL中使用标有数据标注属性以及XVAL参考部分类模型类。
I have model classes in Linq-to-Sql with partial classes marked with data annotation attributes and a reference to xVal.
当我直接绑定,以便模型一切都很正常,都是由XVAL和服务器端仔细检查所产生的JS。
When I bind a view directly to a model everything works great, both the JS generated by xVal and server side double check.
我的很多观点不采取输入到一个特定的模式,所以我设置视图模型类。相反,暴露整个模型实例我公开属性到模型中,我允许/需要的视图设置。
Many of my views don't take input to one specific model, so I am setting up view model classes. Instead of exposing an entire model instance I expose properties into the model that I allow/need to be set by the view.
// 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;
}
}
此方法正确填充视图模型类和仓库可以正确填充记录。
This approach populates the view model class correctly and the repository can populate the record correctly.
这根本不虽然通过审定拉。我已经看了看发出的客户端code和验证阵列为空XVAL。此外,在服务器端检查IsValid的始终是真实的。
It doesn't pull through the validation at all though. I have looked at the client code emitted and the validation array is empty for xval. Additionally, the server side check for IsValid is always true.
我可以拥有的数据注解虽然拉视图模型的属性,这样的验证,或者我应该做这个法子?
Can I have the data annotations pull though the properties of view model for validation like this, or should I be doing this another way?
推荐答案
如果您使用的谐音,并传入亚型,你仍然需要参赛资格。见如下:
If you use partials, and pass in the subtype, you still need to qualify. See as follows:
<%@ Control Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<MvcWeb.Models.OrderDetail>" %>
<% using (Html.BeginForm()) { %>
<fieldset>
<legend>Fields</legend>
<%= Html.Hidden("OrderId", Model.OrderId) %>
<%= Html.Hidden("ProductId", Model.ProductId)%>
<p>
<label for="Quantity">Quantity:</label>
<%= Html.TextBox("OrderDetails.Quantity", Model.Quantity)%>
<%= Html.ValidationMessage("OrderDetails.Quantity", "*") %>
</p>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
注意该类型订单明细,但我仍然prefixing的处理验证消息。
Notice that the type is OrderDetails, but I'm still prefixing that to deal with validation messages.
这篇关于ASP.NET MVC模型/视图模型验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!