嵌套的视图模型对象字段的ASP.NET MVC3验证 [英] ASP.NET MVC3 Validation of nested view model object fields

查看:84
本文介绍了嵌套的视图模型对象字段的ASP.NET MVC3验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的视图模型:

I have a view model that looks like this:

public class VenueIndexViewModel : BaseViewModel
{
    public VenueAddViewModel Venue;
    ...
}

public class VenueAddViewModel
{
    ...
    [Required(ErrorMessage = "This field is required")]
    public string State { get; set; }
    ...
}

在我看来,我渲染的形式与一个下拉列表此属性,像这样:

In my view, I'm rendering a form with with a drop down list for this property like so:

using (var form = Html.BeginForm())
{ 
    ...
    @Html.DropDownListFor(x => x.Venue.State, Model.GetStates())
    @Html.ValidationMessageFor(x => x.Venue.State)
    ...
}

这工作,但问题是,在视图模型的必需属性似乎被忽略。如果我看HTML,数据val- *属性丢失以及

This works, but the problem is that the the Required attribute on the view model appears to be ignored. If I look at the HTML, the data-val-* attributes are missing as well.

<select id="Venue_State" name="Venue.State">...</select>

不过,如果我改变渲染一个文本框...

However, if I change the rendering to a textbox...

using (var form = Html.BeginForm())
{ 
    ...
    @Html.TextBoxFor(x => x.Venue.State)
    @Html.ValidationMessageFor(x => x.Venue.State)
    ...
}

我看到预期的数据val- *属性和验证工作的:

I see the expected data-val-* attributes and the validation works:

<input data-val="true" 
    data-val-required="This field is required" 
    id="Venue_State" name="Venue.State" type="text" value="">

我要指出,我有其他地方的视图模型使用DropDownListFor用平视图模型(无嵌套对象)和验证工作正常那里,所以我想我已经打了MVC的验证处理的一个bug使用嵌套视图模型时,下拉列表。任何人都可以证实/指教?

I should note that I have other view models elsewhere that use DropDownListFor with a flat view model (no nested objects) and the validation works fine there, so I'm thinking I've hit a bug in the MVC validation handling for drop down lists when using a nested view model. Can anyone confirm / advise?

推荐答案

据我知道你不能对嵌套对象客户端验证。而一个快速谷歌搜索似乎证实。

As far as I know you can't have client side validation on nested objects. And a quick google search seems to confirm that.

http://forums.asp.net/t/1737269.aspx/1

这篇关于嵌套的视图模型对象字段的ASP.NET MVC3验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆