In a ValidationSummary, why are the messages shown in a different order than the order you added errors to the ModelState and how might I fix this?
asp.net mvc is open source so you can see the code for ValidationSummary directly.
http://www.asp.net/mvc/download/
That said, I'm pretty sure ModelState is a dictionary. So if ValidationSummary is iterating over the key/values in the ModelState dictionary looking for errors the order is going to be random.
I downloaded the code at work. From ValidationSummary in MVC/Html/ValidationExtensions.cs:
foreach (ModelState modelState in htmlHelper.ViewData.ModelState.Values) {
foreach (ModelError modelError in modelState.Errors) {
// stuff to build a string with the error
}
}
So it is iterating over the values in the dictionary. And from MSDN:
For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair(TKey, TValue) structure representing a value and its key. The order in which the items are returned is undefined.
and
The order of the values in the Dictionary(TKey, TValue).ValueCollection is unspecified
Emphasis mine.