Fork me on GitHub

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

 

posted @ 2013-07-24 18:55  Halower  阅读(832)  评论(0编辑  收藏  举报