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

前端 未结 2 2011
迷失自我
迷失自我 2021-01-25 16:44

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 a

2条回答
  •  时光取名叫无心
    2021-01-25 17:20

    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 fieldOrder = new List(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)
    {
        
      @foreach (string sortedError in ViewBag.SortedErrors) {
    • @sortedError
    • }
    }

提交回复
热议问题