zoukankan      html  css  js  c++  java
  • MVC自动绑定整数数组

      昨天恰好遇到这个问题,stackoverflow上已经有人回答过了,拿过来在这里做个笔记。当然下面的例子可以修改,我比较喜欢使用ImodelBinder

    自定义模型绑定器

    public class IntArrayModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            if (value == null || string.IsNullOrEmpty(value.AttemptedValue))
            {
                return null;
            }
    
            return value
                .AttemptedValue
                .Split(',')
                .Select(int.Parse)
                .ToArray();
        }
    }

     使用方法

         [HttpPost]
            public ActionResult ActionName([ModelBinder(typeof(IntArrayModelBinder))]int[] arr)
            {
                  //TODO...
            }

     虽然在stackoverFlow中没有提到,但是这样还是非常的不智能,我们想要这样:

           [HttpPost]
            public ActionResult ActionName(int[] arr)
            {
                  //TODO...
            }

    怎么办呢,其实非常简单就是在Application_Start()注册一下自定义的绑定器就可以了。

     

  • 相关阅读:
    Sqlsugar中使用Codefrist创建数据库
    EFCore中CoreFrist多个上下文
    高并发
    优先级反转
    二叉树算法
    使用AJAX上传图片
    Entity Framework
    .Net面试题
    LC 1515. Best Position for a Service Centre (Simulated Annealing)
    git
  • 原文地址:https://www.cnblogs.com/rohelm/p/3211729.html
Copyright © 2011-2022 走看看