ASP.NET MVC ajax数组,模型绑定问题。

当我们在做批量删除的时候,很多情况下,我们只拿到checkbox 的Value。把checkbox中的value放在一个Array中。然后ajax到MVC的控制器中。

在ajax array的时候数据如下图:

可以发现,因为新增了一对儿中括号,模型绑定就失败了,我们可以想到重写MVC的BindModel

重写代码如下:

 public class JQueryBundler : DefaultModelBinder//这里要集成DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType.IsEnumerableType())
            {
                var key = bindingContext.ModelName + "[]";
                var valueResult = bindingContext.ValueProvider.GetValue(key);
                if (valueResult != null && !string.IsNullOrEmpty(valueResult.AttemptedValue))
                {
                    bindingContext.ModelName = key;
                }
            }
            return base.BindModel(controllerContext, bindingContext);
        }
    }

其中:IsEnumerableType()是System.Type的一个扩展方法.具体实现如下:

/// <summary>
        /// 判断对象是否是Enumber类型的
        /// </summary>
        /// <param name="enumerableType"></param>
        /// <returns></returns>
        public static bool IsEnumerableType(this Type enumerableType)
        {
            return (FindGenericType(typeof(IEnumerable<>), enumerableType) != null);
        }
        public static Type FindGenericType(this Type definition, Type type)
        {
            while ((type != null) && (type != typeof(object)))
            {
                if (type.IsGenericType && (type.GetGenericTypeDefinition() == definition))
                {
                    return type;
                }
                if (definition.IsInterface)
                {
                    foreach (Type type2 in type.GetInterfaces())
                    {
                        Type type3 = FindGenericType(definition, type2);
                        if (type3 != null)
                        {
                            return type3;
                        }
                    }
                }
                type = type.BaseType;
            }
            return null;
        }

最后需要在:Global.asax中加入下面这句话在MVC启动的时候使用我们自定义的模型绑定:

ModelBinders.Binders.DefaultBinder = new 你的模型绑定的类

 

 

 

 

更新:

MVC5中直接可以用数组接收:

Public ActionResult Save(int[] Id)

{

...Your code

  return View();

}

posted @ 2016-03-09 14:57  Shauna.Vayne  阅读(530)  评论(0编辑  收藏  举报