ViewModel列表中每个项目的数据验证 [英] Data validation for every item in a list of my ViewModel

查看:82
本文介绍了ViewModel列表中每个项目的数据验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要使用Regex进行验证,通常需要执行以下操作:

To make a validation with a Regex, I usually do:

// In my ViewModel
[RegularExpression("MyRegex", ErrorMessageResourceName = "MyErrorMessage")]
public string MyField { get; set; }

和HTML助手

@Html.TextBoxFor(model => model.MyField)

生成如下所示的标记:

<input type="text" class="valid" name="MyField" value="" id="MyField" data-val="true" data-val-regex-pattern="MyRegex" data-val-regex="MyErrorMessage"></input>

问题是我想拥有动态数量的字段并正在使用

The problem is that I want to have a dynamic number of fields and am now using

// In my ViewModel
[RegularExpression("MyRegex", ErrorMessageResourceName = "MyErrorMessage")]
public IList<string> MyField { get; set; }

这次

@Html.TextBoxFor(model => model.MyField[0])

将生成(不带正则表达式html属性)

will generate (without the regex html attributes)

<input id="MyField_0_" type="text" value="" name="MyField[0]"></input>

如何确保 data-val 当在ViewModel中绑定具有DataAnnotation验证属性的列表的元素时,会创建html属性?

How can I ensure that data-val html attributes are created when binding elements of a list that has a DataAnnotation validation attribute in my ViewModel?

推荐答案

一种将数据注释应用于列表元素的方法。您需要做的是创建一个包装类,然后将数据注释应用于包装类中的元素,如下所示:

There isn't really a way for Data Annotations to apply to the elements of a list. What you would have to do is create a wrapper class and apply the Data Annotation to the elements in the wrapper class, like so:

public IList<MyField> MyFields {get;set;}

public class MyField
{
    [RegularExpression("MyRegex", ErrorMessageResourceName = "MyErrorMessage")]
    public string Value
}

用法:

@Html.TextBoxFor(model => model.MyFields[0].Value)

这篇关于ViewModel列表中每个项目的数据验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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