【问题标题】:MVC Model Binding - Validate EVERY property?MVC 模型绑定 - 验证每个属性?
【发布时间】:2012-10-09 13:52:27
【问题描述】:

我有一些通用验证,我希望将毯子应用于每个模型上的每个字符串属性。我正在考虑继承 DefaultModelBinder 并通过覆盖 BindProperty 方法来添加逻辑。这样做合适吗?

【问题讨论】:

    标签: c# asp.net-mvc-3 validation


    【解决方案1】:
    1. 编写您自己的自定义模型绑定器。
    2. 使用反射获取所有属性
    3. 检查属性是否为string类型
    4. 使用反射获取属性的值
    5. 运行自定义验证并将验证错误添加到ModelState

    示例

    public class MyCustomModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            foreach (var propertyInfo in typeof(bindingContext.Model.GetType().GetProperties(BindingFlags.Public|BindingFlags.Instance))
            {
               if (propertyInfo.PropertyType == typeof(string)) 
               {
                   var value = propertyInfo.GetValue(bindingContext.Model);
                   // validate
                   // append to ModelState if validation failed
                   bindingContext.ModelState.AddModelError(propertyInfo.Name, "Validation Failed");
               }
            }
        }
    }
    

    使用模型绑定器

    public ActionResult MyActionMethod([ModelBinder(typeof(MyCustomModelBinder ))] ModelType model)
    {
      // ModelState.IsValid is false if validation fails
    }
    

    更多信息

    【讨论】:

    • 你为什么建议我自己写而不是继承默认的?此外,我不想要求每个人都在每个操作方法中添加一个属性来触发行为。它应该默认发生。
    【解决方案2】:

    子类化 DefaultModelBinder 并覆盖 BindProperty 对我来说效果很好。调用 base.BindProperty 可确保模型的属性已设置,然后我可以对其进行评估以进行全局验证。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-17
      • 2012-12-08
      • 2014-07-21
      • 2013-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多