在asp.net mvc的使用IDataErrorInfo的 [英] using IDataErrorInfo in asp.net mvc

查看:118
本文介绍了在asp.net mvc的使用IDataErrorInfo的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经得到了我想要使用IDataErrorInfo的接口的在asp.net网站解释。

I've got a simple address entry app that I'm trying to use the IDataErrorInfo interface as explained on the asp.net site.

它可以独立被验证,但不是那么好当一些项目寄人篱下项目的伟大工程。例如,验证邮政$ C $,c取决于该国:

It works great for items that can be validated independently, but not so well when some items depend on others. For example, validating the postal code depends on the country:

    private string _PostalCode;
    public string PostalCode
    {
        get
        {
            return _PostalCode;
        }
        set
        {
            switch (_Country)
            {
                case Countries.USA:
                    if (!Regex.IsMatch(value, @"^[0-9]{5}$"))
                        _errors.Add("PostalCode", "Invalid Zip Code");
                    break;
                case Countries.Canada:
                    if (!Regex.IsMatch(value, @"^([a-z][0-9][a-z]) ?([0-9][a-z][0-9])$", RegexOptions.IgnoreCase))
                        _errors.Add("PostalCode", "Invalid postal Code");
                    break;
                default:
                    throw new ArgumentException("Unknown Country");
            }
            _PostalCode = value;
        }
    }

所以,你只能验证邮政code国已定之后,但似乎没有控制该命令的方式。

So you can only validate the postal code after the country has been set, but there seems to be no way of controlling that order.

我可以用从IDataErrorInfo的错误字符串,但并不在Html.ValidationMessage显示该字段旁边。

I could use the Error string from IDataErrorInfo, but that doesn't show up in the Html.ValidationMessage next to the field.

推荐答案

有关更复杂的业务规则验证,而不是类型验证它也许是更好地实现设计模式,例如一个服务层。您可以检查ModelState中,并根据您的逻辑添加错误。

For more complex business rule validation, rather than type validation it is maybe better to implement design patterns such as a service layer. You can check the ModelState and add errors based on your logic.

您可以在这里查看模式罗布Conroys例如

You can view Rob Conroys example of patterns here

http://www.asp.net/learn/mvc/教程29 cs.aspx

这篇文章在数据注释AY也是有用的。

This article on Data Annotations ay also be useful.

http://www.asp.net/learn/mvc/教程39 cs.aspx

希望这有助于。

这篇关于在asp.net mvc的使用IDataErrorInfo的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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