Neelima Ediga
Neelima Ediga

Reputation: 356

DataAnnotations DisplayAttributes Order property is not working in MVC

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.

Upvotes: 0

Views: 1758

Answers (2)

Neelima Ediga
Neelima Ediga

Reputation: 356

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!

Upvotes: 0

sjb-sjb
sjb-sjb

Reputation: 1195

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

Upvotes: 1

Related Questions