gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:42:41 25 4
gpt4 key购买 nike

我试图找出验证一页结帐的最佳方法。
它包含了 :

  • 收货地址
  • 账单地址

  • 地址类明显包含 First Name , Last Name , Street1 , Street2 , City , State , Zip , Phone等等。

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

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

    所以我想将摘要显示为:
     "Your shipping address is incomplete"

    并以红色突出显示 ZipCity .

    我想我必须做一个完全自定义的 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.



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

    最佳答案

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

    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)
    {
    ...
    }
    }
    }

    关于asp.net-mvc - 地址字段的自定义 ASP.NET MVC 验证摘要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1815005/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com