集合的验证摘要

发布于 2024-08-25 08:55:18 字数 3412 浏览 3 评论 0原文

编辑:将此问题升级到 MVC 2.0
使用 asp.net MVC 2.0 是否有一种现有的方法来创建对于包含集合的模型有意义的验证摘要?如果没有,我可以创建自己的验证摘要示例

模型:

public class GroupDetailsViewModel
{
    public string GroupName { get; set; }
    public int NumberOfPeople { get; set; }
    public List<Person> People{ get; set; }
}

public class Person
{
    [Required(ErrorMessage = "Please enter your Email Address")]
    [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage = "Please enter a valid Email Address")]
    public string EmailAddress { get; set; }

    [Required(ErrorMessage = "Please enter your Phone Number")]
    public string Phone { get; set; }

    [Required(ErrorMessage = "Please enter your First Name")]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Please enter your Last Name")]
    public string LastName { get; set; }
}

如果未输入任何内容,现有摘要 <%=Html.ValidationSummary %> 看起来像这样。

在继续下一步之前必须更正以下错误
* 请输入您的电子邮件地址
* 请输入您的电话号码
* 请输入您的名字
* 请输入您的姓氏
* 请输入您的电子邮件地址
* 请输入您的电话号码
* 请输入您的名字
* 请输入您的姓氏

设计要求插入标题,如下所示:

在继续下一步之前必须更正以下错误
第 1 个人
* 请输入您的电子邮件地址
* 请输入您的电话号码
* 请输入您的名字
* 请输入您的姓氏
第 2 个人
* 请输入您的电子邮件地址
* 请输入您的电话号码
* 请输入您的名字
* 请输入您的姓氏

* 请根据 Pharcyde 的回答

public static MvcHtmlString NestedValidationSummary(this HtmlHelper helper)
{
    if (helper.ViewData.ModelState.IsValid)
        return MvcHtmlString.Empty;

    // create datastructure to group error messages under a given key (blank key is for general errors)
    var errors = new Dictionary<string,List<string>>();
    foreach (KeyValuePair<string, ModelState> keyPair in helper.ViewData.ModelState)
    {
        foreach (ModelError error in keyPair.Value.Errors)
        {
            //determine the 'key' for the group in which this error belongs
            var key = keyPair.Key.Split(']')[0];
            if (key.Contains("People["))
                key = "Person " + key.Split('[')[1];
            else
                key = string.Empty;

            if(!errors.ContainsKey(key))
                errors.Add(key,new List<string>());
            //now add message using error.ErrorMessage property
            errors[key].Add(error.ErrorMessage);
        }
    }

    // generate the HTML
    var ul = new TagBuilder("ul");
    foreach (KeyValuePair<string, List<string>> errorPair in errors.OrderBy(p=>p.Key))
    {
        var li = new TagBuilder("li");
        if(!string.IsNullOrEmpty(errorPair.Key))
            li.InnerHtml += string.Format("<p class=\"no-bottom-margin\"><strong>{0}</strong></p>",errorPair.Key);
        var innerUl = new TagBuilder("ul");
        foreach (var message in errorPair.Value)
        {
            var innerLi = new TagBuilder("li");
            innerLi.InnerHtml = message;
            innerUl.InnerHtml += innerLi.ToString(TagRenderMode.Normal);
        }
        li.InnerHtml += innerUl.ToString(TagRenderMode.Normal);
        ul.InnerHtml += li.ToString(TagRenderMode.Normal);
    }

    return MvcHtmlString.Create(ul.ToString(TagRenderMode.Normal));
}

EDIT: upgraded this question to MVC 2.0
With asp.net MVC 2.0 is there an existing method of creating Validation Summary that makes sense for models containing collections? If not I can create my own validation summary

Example Model:

public class GroupDetailsViewModel
{
    public string GroupName { get; set; }
    public int NumberOfPeople { get; set; }
    public List<Person> People{ get; set; }
}

public class Person
{
    [Required(ErrorMessage = "Please enter your Email Address")]
    [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage = "Please enter a valid Email Address")]
    public string EmailAddress { get; set; }

    [Required(ErrorMessage = "Please enter your Phone Number")]
    public string Phone { get; set; }

    [Required(ErrorMessage = "Please enter your First Name")]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Please enter your Last Name")]
    public string LastName { get; set; }
}

The existing summary <%=Html.ValidationSummary %> if nothing is entered looks like this.

The following error(s) must be corrected before proceeding to the next step
* Please enter your Email Address
* Please enter your Phone Number
* Please enter your First Name
* Please enter your Last Name
* Please enter your Email Address
* Please enter your Phone Number
* Please enter your First Name
* Please enter your Last Name

The design calls for headings to be inserted like this:

The following error(s) must be corrected before proceeding to the next step
Person 1
* Please enter your Email Address
* Please enter your Phone Number
* Please enter your First Name
* Please enter your Last Name
Person 2
* Please enter your Email Address
* Please enter your Phone Number
* Please enter your First Name
* Please enter your Last Name

Answer Based on Pharcyde's answer.

public static MvcHtmlString NestedValidationSummary(this HtmlHelper helper)
{
    if (helper.ViewData.ModelState.IsValid)
        return MvcHtmlString.Empty;

    // create datastructure to group error messages under a given key (blank key is for general errors)
    var errors = new Dictionary<string,List<string>>();
    foreach (KeyValuePair<string, ModelState> keyPair in helper.ViewData.ModelState)
    {
        foreach (ModelError error in keyPair.Value.Errors)
        {
            //determine the 'key' for the group in which this error belongs
            var key = keyPair.Key.Split(']')[0];
            if (key.Contains("People["))
                key = "Person " + key.Split('[')[1];
            else
                key = string.Empty;

            if(!errors.ContainsKey(key))
                errors.Add(key,new List<string>());
            //now add message using error.ErrorMessage property
            errors[key].Add(error.ErrorMessage);
        }
    }

    // generate the HTML
    var ul = new TagBuilder("ul");
    foreach (KeyValuePair<string, List<string>> errorPair in errors.OrderBy(p=>p.Key))
    {
        var li = new TagBuilder("li");
        if(!string.IsNullOrEmpty(errorPair.Key))
            li.InnerHtml += string.Format("<p class=\"no-bottom-margin\"><strong>{0}</strong></p>",errorPair.Key);
        var innerUl = new TagBuilder("ul");
        foreach (var message in errorPair.Value)
        {
            var innerLi = new TagBuilder("li");
            innerLi.InnerHtml = message;
            innerUl.InnerHtml += innerLi.ToString(TagRenderMode.Normal);
        }
        li.InnerHtml += innerUl.ToString(TagRenderMode.Normal);
        ul.InnerHtml += li.ToString(TagRenderMode.Normal);
    }

    return MvcHtmlString.Create(ul.ToString(TagRenderMode.Normal));
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

江湖彼岸 2024-09-01 08:55:18

您将必须扩展 HtmlHelper 方法并推出您自己的方法。以下是对于您需要分组依据的情况非常重要的代码:

//HtmlHelper being extended
if(helper.ViewData.ModelState.IsValid)
{
    foreach(KeyValuePair<string,ModelState> keyPair in helper.ViewData.ModelState)
    {     
        //add division for group by here using keyPair.Key property (would be named "Person" in your case).

        foreach(ModelError error in keyPair.Value.Errors)
        {
            //now add message using error.ErrorMessage property
        }
    }
}

You are going to have to extend the HtmlHelper methods and roll your own. Heres the bit of code that is important for your situation where you need a group by:

//HtmlHelper being extended
if(helper.ViewData.ModelState.IsValid)
{
    foreach(KeyValuePair<string,ModelState> keyPair in helper.ViewData.ModelState)
    {     
        //add division for group by here using keyPair.Key property (would be named "Person" in your case).

        foreach(ModelError error in keyPair.Value.Errors)
        {
            //now add message using error.ErrorMessage property
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文