0

I am setting the values for DataAnnotations DisplayAttributes Order property in my model object. However, it seems to be not working.

I am on .Net Framework 4.7 and MVC 5. As per the below link, its supposed to work.

https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.displayattribute.order?view=netframework-4.7.2

    [Required(ErrorMessage = "Case is required.")]
    [Display(Name = "Case", Order = -98)]
    public int CaseId { get; set; }

    [Required(ErrorMessage = "Phase is required.")]
    [Display(Name = "Phase", Order = -99)]
    public int PhaseId { get; set; }

Since the default order weight is 0, I used negative values to set it in the order I want. Irrespective of what Order weight I specify, the validation messages are always displayed in the order of the property declaration in the model.

Any suggestions or inputs please?

Thanks in advance.

Neelima Ediga
  • 346
  • 1
  • 5
  • 19

2 Answers2

1

The DisplayAttribute controls the order of columns in a display, not the ordering of validation messages.

You might try putting the error messages next to the controls as described in Display error message on the view from controller asp.net mvc 5

sjb-sjb
  • 1,112
  • 6
  • 14
  • Oh ok, got it. But for the link, I don't think its helpful in my case. Thanks for your help. – Neelima Ediga Jan 25 '19 at 17:05
  • What you could do is use reflection to iterate through the properties, get the Display attribute from each one and look at the Order property of the attribute. Then you could sort the error messages with that. – sjb-sjb Feb 04 '19 at 21:12
0

This was helpful to rearrange the error messages order.

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

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>
}

Hope this helps someone else. Thanks!

Neelima Ediga
  • 346
  • 1
  • 5
  • 19