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

  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM