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()注册一下自定义的绑定器就可以了。

     

  • 相关阅读:
    python 操作mysql
    openstack 与 VMware(vSphere) 不同
    python redis 实现订阅发布
    python redis 管道
    python rabbitMQ 实现RPC
    python 连接redis
    使用gdb
    在应用程序中如何打印调用栈
    如何使用coredump
    linux中常用命令
  • 原文地址:https://www.cnblogs.com/rohelm/p/3211729.html
Copyright © 2011-2022 走看看