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();

}

转载于:https://www.cnblogs.com/jolab/p/5258207.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值