@Html.ValidationSummary() - how to set order of error messages

爷,独闯天下 提交于 2019-12-02 05:07:39

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

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.

Controller code:

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();

Then in the view:

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

I think a better way of doing this is to order the properties in your model in the same order you that you would like to display your validation messages:

public class Ingredients
{
    [Required]
    public string Vegetable { get; set; }
    [Required]
    public string Starch { get; set; }
    [Required]
    public string Meat { get; set; }
    [Required]
    public string Fruit { get; set; }
  }

This will display a message in the following order:

  • The Vegetable field is required.
  • The Starch field is required.
  • The Meat field is required.
  • The Fruit field is required.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!