昨天恰好遇到这个问题,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()注册一下自定义的绑定器就可以了。

 

相关文章:

  • 2022-03-09
  • 2022-01-18
  • 2021-11-27
  • 2021-09-19
  • 2021-09-04
  • 2021-12-09
  • 2022-12-23
猜你喜欢
  • 2022-01-10
  • 2022-12-23
  • 2021-11-05
  • 2022-12-23
  • 2021-07-12
  • 2021-10-13
  • 2021-09-20
相关资源
相似解决方案