加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 地址字段的自定义ASP.NET MVC验证摘要

发布时间:2020-12-16 06:42:28 所属栏目:asp.Net 来源:网络整理
导读:我正试图找出验证单页结帐的最佳方法. 它包含 : 船舶地址 帐单地址 等 地址类明显包含名字,姓氏,街道1,街道2,城市,州,邮编,电话等. 假设用户在输入任何内容之前单击“确定” – 然后您最终会遇到十几个或更多验证错误,从而为您提供一大块看起来很难看的红色
我正试图找出验证单页结帐的最佳方法.
它包含 :

>船舶地址
>帐单地址
>等

地址类明显包含名字,姓氏,街道1,街道2,城市,州,邮编,电话等.

假设用户在输入任何内容之前单击“确定” – 然后您最终会遇到十几个或更多验证错误,从而为您提供一大块看起来很难看的红色文本.

我想将地址验证为单个实体,并在适当时给出智能错误 – 例如“不完整地址”或更具体的错误.但我仍然希望能够突出显示有问题的每个字段.我现在看不到一种简单的方法,因为显然Html.ValidationSummary助手会显示每个字段.

所以我想把摘要显示为:

"Your shipping address is incomplete"

并以红色Zip和City突出显示.

我想我必须做一个完全自定义的ValidationSummary,甚至可能是一个完全自定义的数据结构.

任何验证框架都可以使这样的摘要更容易,其中摘要应显示智能摘要,而不仅仅是每个字段错误.

编辑:MVC 2 RC现在支持模型级错误.

ValidationSummary now supports
overloads where only model-level
errors are displayed. This is useful
if you are displaying validation
messages inline next to each form
field. Previously,these messages
would be duplicated in the validation
summary. With these new changes,you
can have the summary display an
overall validation message (ex. “There
were errors in your form submission”)
as well as a list of validation
messages which don’t apply to a
specific field.

有人得到了如何做到这一点的实际样本?

解决方法

您可以使用复合Address属性并将整个地址验证为一个单元:

public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
    public string Zip { get; set; }
}

public class Order
{
    [Required]
    public string FirstName { get; set; }

    [Required]
    public string LastName { get; set; }

    [AddressRequired("Your shipping address is incomplete")]
    public Address ShipTo { get; set; }

    [AddressRequired("Your billing address is incomplete")]
    public Address BillTo { get; set; }

    // you could do this if you still need 1:1 mapping for model binding
    public string ShippingCity
    {
        get { return ShipTo.City; }
        set { ShipTo.City = value; }
    }
}

验证属性看起来像这样:

public class AddressRequiredAttribute : ValidationAttribute
{
    ...

    public override bool IsValid(object value)
    {
        var address = value as Address;

        if (address != null)
        {
            ...
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读