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

牧云@^-^@ 提交于 2019-12-07 13:45:07

问题


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.

回答1:


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.




回答2:


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" });



回答3:


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 

    }



回答4:


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());



来源:https://stackoverflow.com/questions/3912728/how-to-specify-order-of-data-annotation-errors-in-html-validationsummary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!