zoukankan      html  css  js  c++  java
  • asp.net mvc int[] 和 string[] 自定义数组绑定

    新建类,int[]数组模型绑定

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace Koukou.Admin.ModelBinder
    {
        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();
            }
        }
    }
    

    string[] 数组模型绑定

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace Koukou.Admin.ModelBinder
    {
        public class StringArrayModelBinder : 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(new string[] { ",", Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                // 逗号“,” 和 换行符 作为分隔
            }
        }
    }
    

    在global.asax的Application_Start注册

    protected void Application_Start()
            {
                AreaRegistration.RegisterAllAreas();
    
                RegisterGlobalFilters(GlobalFilters.Filters);
                RegisterRoutes(RouteTable.Routes);
    
    //自定义model绑定
                ModelBinders.Binders.Add(typeof(int[]), new ModelBinder.IntArrayModelBinder());
                ModelBinders.Binders.Add(typeof(string[]), new ModelBinder.StringArrayModelBinder());
            }
    

      

      

  • 相关阅读:
    [YTU]_2417 C语言习题 字符串长度
    最小生成树学习笔记
    后缀数组学习笔记
    网络流的几个小优化
    面向对象
    Manacher(马拉车)学习笔记
    EXKMP学习笔记QAQ
    GDOI DAY1游记
    GDOI--DAY2 游记
    caioj:1348: [NOIP普及组2012]质因数分解 C++
  • 原文地址:https://www.cnblogs.com/gezifeiyang/p/3983280.html
Copyright © 2011-2022 走看看