开发者

How to specify order of Data Annotation errors in Html.ValidationSummary

开发者 https://www.devze.com 2023-01-20 02:31 出处:网络
I\'m displaying errors on my form with the use of <%= Html.ValidationSummary(\"Please review the errors below\") %>

I'm displaying errors on my form with the use of

<%= Html.ValidationSummary("Please review the errors below") %>

My domain object inherits from a base class and I am finding that the base class data annotation properties are being displayed at the bottom of the list. This goes against the order in which they appear in my form.

Is there any way of specifying what order the errors should be displayed?

Example:

public class 开发者_运维百科ClassA { [Required]public string AProperty; }
public class ClassB : ClassA { [Required]public string BProperty; }

My form (strongly typed view of ClassB):

AProperty: <%= Html.TextBoxFor(m => m.AProperty) %>
BProperty: <%= Html.TextBoxFor(m => m.BProperty) %>

Validation errors appear as:

The BProperty is required.
The AProperty is required.


I've written an extension for this:

public static void OrderByKeys(this ModelStateDictionary modelStateDictionary, IEnumerable<string> keys)
{
    ModelStateDictionary result = new ModelStateDictionary();
    foreach (string key in keys)
    {
        if (modelStateDictionary.ContainsKey(key) && !result.ContainsKey(key))
        {
            result.Add(key, modelStateDictionary[key]);
        }
    }
    foreach (string key in modelStateDictionary.Keys)
    {
        if (!result.ContainsKey(key))
        {
            result.Add(key, modelStateDictionary[key]);
        }
    }
    modelStateDictionary.Clear();
    modelStateDictionary.Merge(result);
}

Which you can use by:

ModelState.OrderByKeys(new[] { "AProperty", "BProperty" });


Nope. Reflection is used to get all the DataAnnotations and they always appear in the order the properties would appear with a call to typeof(MagicSocks).GetTYpe().GetProperties(). In your case I'm pretty sure derived class properties will always appear before base type properties.

You have to write your own helper and our own attributes to display the validation errors in the order you choose.


i am not sure my answer is right or wrong, you can try this way.

   public ActionResult yourAction(your params)
    { 
           if (!ModelState.IsValid)
            {
                var errs = from er in tmpErrs
                           orderby er.Key
                           select er;

                ModelState.Clear();

                foreach (var err in errs)
                {
                    ModelState.Add(err);
                }
            }
    // your code 

    }


Try this filter attribute which orders the model state according to the request's form keys.

using System.Linq;
using System.Web.Mvc;

namespace 
{
    public class OrderedModelStateAttribute : FilterAttribute, IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var modelState = filterContext.Controller.ViewData.ModelState;
            var orderedModelState = new ModelStateDictionary();

            foreach (var key in filterContext.HttpContext.Request.Form.Keys.Cast<string>()
                                             .Where(
                                                 key =>
                                                 modelState.ContainsKey(key) && !orderedModelState.ContainsKey(key)))
            {
                orderedModelState.Add(key, modelState[key]);
            }

            foreach (var key in modelState.Keys.Where(key => !orderedModelState.ContainsKey(key)))
            {
                orderedModelState.Add(key, modelState[key]);
            }

            modelState.Clear();
            modelState.Merge(orderedModelState);
        }

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
        }
    }
}

Use the following code to add the filter to all Actions: filters.Add(new OrderedModelStateAttribute());


I had this same problem and it wasn't feasible to create a new view model - also if you have custom model binders, these will appear at the end of the validation summary regardless. I expanded on Aphize answer, rather than pass it a list of property names you can pass it the form keys - this will ensure the order is the same as they appear in the form e.g.

ModelState.OrderByKeys(Request.Form.AllKeys);

This worked for me and I created an attribute to do this.. ( I had to do some tweaking to deal with the custom binders but here it is without that):

public class ForceValidationErrorOrderAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var allFormKeys = filterContext.HttpContext.Request.Form.AllKeys;
        var modelStateDictionary = filterContext.Controller.ViewData.ModelState;

        ModelStateDictionary result = new ModelStateDictionary();
        foreach (string key in allFormKeys)
        {
            if (modelStateDictionary.ContainsKey(key) && !result.ContainsKey(key))
            {
                result.Add(key, modelStateDictionary[key]);
            }
        }
        foreach (string key in modelStateDictionary.Keys)
        {
            if (!result.ContainsKey(key))
            {
                result.Add(key, modelStateDictionary[key]);
            }
        }
        modelStateDictionary.Clear();
        modelStateDictionary.Merge(result);
        }
    }

And then on the controller action method:

    [ForceValidationErrorOrder]
    public ActionResult Apply(ApplicationViewModel viewModel)
0

精彩评论

暂无评论...
验证码 换一张
取 消