@ Html.ValidationSummary()-如何设置错误消息的顺序 [英] @Html.ValidationSummary() - how to set order of error messages

查看:158
本文介绍了@ Html.ValidationSummary()-如何设置错误消息的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个表单元素.我们将它们称为RadioA,RadioB和Dropdown.在模型中,它们是按此顺序创建的,并以该顺序显示在视图中,并根据需要指定每个错误信息.然后在视图中,我使用:

I have three form elements. We'll call them RadioA, RadioB, and Dropdown. In the Model they are created in that order, and presented in the View in that order, and specified as required with a unique error message for each. Then in the view, I use:

@Html.ValidationSummary()

但是错误消息又回来了:

But the error messages come back:

  • 需要下拉
  • RadioA是必需的
  • RadioB是必需的

在此线程上,我得知我们确实对这些错误消息返回的顺序没有太多控制.一些人提出了有关如何破解此问题的建议,但我无法让他们中的任何一个起作用.

On this thread, I am learning that we really don't have much control over the order in which these error messages come back. A few people gave suggestions on how to hack this, but I can't get any of them to work.

有什么想法吗?我应该只使用jQuery并以老式的方式验证每个表单项吗?

Any ideas? Should I just use jQuery and validate each form item the old-fashioned way?

推荐答案

我已纠正. mhapps提供的答案就像一个魅力.这是最后的答案.我引用他:

I stand corrected. The answer provided by mhapps worked like a charm. It's the last answer. I quote him:

我遇到了这个问题,为了迅速解决,我重新创建了如上所述的验证摘要,并使用ViewBag通过引用有序字段名称的数组以正确的顺序存储错误.并不是特别好,但是我当时能想到的最快的东西. Razor/MVC3.

I had this problem, and to solve it quickly I recreated the validation summary like above and used ViewBag to store the errors in the correct order by referencing an array of ordered field names. Not particularly nice but the fastest thing I could think of at the time. Razor/MVC3.

控制器代码:

List<string> fieldOrder = new List<string>(new string[] { 
"Firstname", "Surname", "Telephone", "Mobile", "EmailAddress" })
.Select(f => f.ToLower()).ToList();

ViewBag.SortedErrors = ModelState
   .Select(m => new { Order = fieldOrder.IndexOf(m.Key.ToLower()), Error = m.Value})
   .OrderBy(m => m.Order)
   .SelectMany(m => m.Error.Errors.Select(e => e.ErrorMessage))
   .ToArray();

然后在视图中:

@if (!ViewData.ModelState.IsValid)
{
    <div class="validation-summary-errors">  
    <ul>
        @foreach (string sortedError in ViewBag.SortedErrors)
        {
            <li>@sortedError</li> 
        }
    </ul>
    </div>
}

这篇关于@ Html.ValidationSummary()-如何设置错误消息的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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