zoukankan      html  css  js  c++  java
  • 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();

    }

  • 相关阅读:
    Linux下安装vmtools的语句
    [WP]BugkuCtf
    Linux文件属性及权限
    学习pwn的前提工作及部分解决方案
    windows环境下MySQL mysql-5.7.17-winx64 (社区服务版,community server)安装教程
    ubuntu14.04 LTS 更新国内网易163源
    session cookie
    java collection map
    重温 总结 maven几个重要概念
    java通信
  • 原文地址:https://www.cnblogs.com/jolab/p/5258207.html
Copyright © 2011-2022 走看看