模型绑定逗号分隔查询字符串参数

时间:2012-03-06 13:24:19

标签: asp.net-mvc-3 model-binding

如何绑定逗号分隔值

的查询字符串参数
http://localhost/Action?ids=4783,5063,5305

到期望列表的控制器操作?

public ActionResult Action(List<long> ids)
{
    return View();
}
控制器操作中的

注意! ids必须是一个列表(或基于IEnumerable的东西),因此不接受string ids作为答案,因为这些参数传递给许多人动作和将字符串解析为数组会增加不必要的噪音。

4 个答案:

答案 0 :(得分:34)

这是我在archil的回答中使用的Nathan Taylor解决方案的改进版本。

  1. Nathan的活页夹只能绑定复杂模型的子属性, 而我的也可以绑定各个控制器参数。
  2. 我的活页夹还可以通过返回一个来正确处理空参数 数组的实际空实例或IEnumerable。
  3. 要将其连接起来,您可以将其附加到单个Controller参数:

    [ModelBinder(typeof(CommaSeparatedModelBinder))]
    

    ...或者将其设置为global.asax.cs中的Application_Start中的全局默认绑定器:

    ModelBinders.Binders.DefaultBinder = new CommaSeparatedModelBinder();
    

    在第二种情况下,它将尝试处理所有IEnumerables并回退到其他所有的ASP.NET MVC标准实现。

    看哪:

    public class CommaSeparatedModelBinder : DefaultModelBinder
    {
        private static readonly MethodInfo ToArrayMethod = typeof(Enumerable).GetMethod("ToArray");
    
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            return BindCsv(bindingContext.ModelType, bindingContext.ModelName, bindingContext)
                    ?? base.BindModel(controllerContext, bindingContext);
        }
    
        protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
        {
            return BindCsv(propertyDescriptor.PropertyType, propertyDescriptor.Name, bindingContext)
                    ?? base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
        }
    
        private object BindCsv(Type type, string name, ModelBindingContext bindingContext)
        {
            if (type.GetInterface(typeof(IEnumerable).Name) != null)
            {
                var actualValue = bindingContext.ValueProvider.GetValue(name);
    
                if (actualValue != null)
                {
                    var valueType = type.GetElementType() ?? type.GetGenericArguments().FirstOrDefault();
    
                    if (valueType != null && valueType.GetInterface(typeof(IConvertible).Name) != null)
                    {
                        var list = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(valueType));
    
                        foreach (var splitValue in actualValue.AttemptedValue.Split(new[] { ',' }))
                        {
                                if(!String.IsNullOrWhiteSpace(splitValue))
                                    list.Add(Convert.ChangeType(splitValue, valueType));
                        }
    
                        if (type.IsArray)
                            return ToArrayMethod.MakeGenericMethod(valueType).Invoke(this, new[] { list });
                        else
                            return list;
                    }
                }
            }
    
            return null;
        }
    }
    

答案 1 :(得分:22)

默认模型绑定器期望简单类型列表的格式为

name=value&name=value2&name=value3

要使用内置绑定,您应该将查询字符串更改为

Action?ids=4783&ids=5063&ids=5305

或创建自定义模型绑定器。您可以查看following article(来自那里的代码)

public class CommaSeparatedValuesModelBinder : DefaultModelBinder
{
    private static readonly MethodInfo ToArrayMethod = typeof(Enumerable).GetMethod("ToArray");

    protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
    {
        if (propertyDescriptor.PropertyType.GetInterface(typeof(IEnumerable).Name) != null)
        {
            var actualValue = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name);

            if (actualValue != null && !String.IsNullOrWhiteSpace(actualValue.AttemptedValue) && actualValue.AttemptedValue.Contains(","))
            {
                var valueType = propertyDescriptor.PropertyType.GetElementType() ?? propertyDescriptor.PropertyType.GetGenericArguments().FirstOrDefault();

                if (valueType != null && valueType.GetInterface(typeof(IConvertible).Name) != null)
                {
                    var list = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(valueType));

                    foreach (var splitValue in actualValue.AttemptedValue.Split(new[] { ',' }))
                    {
                        list.Add(Convert.ChangeType(splitValue, valueType));
                    }

                    if (propertyDescriptor.PropertyType.IsArray)
                    {
                        return ToArrayMethod.MakeGenericMethod(valueType).Invoke(this, new[] { list });
                    }
                    else
                    {
                        return list;
                    }
                }
            }
        }

        return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
    }
}

答案 2 :(得分:2)

Archils的回答提供了一些如何实现我自己的模型绑定器的想法。我能够略微简化源代码,因为不需要非常通用的CSV支持。我没有将收到的数据设置为List<int>,而是将它放到课堂上。

模型绑定器

public class FarmModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType == typeof(FarmModel))
        {
            var newBindingContext = new ModelBindingContext()
            {
                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(
                () => CreateFarmModel(controllerContext, bindingContext),
                typeof(FarmModel)
                ),
                ModelState = bindingContext.ModelState,
                ValueProvider = bindingContext.ValueProvider
            };

            return base.BindModel(controllerContext, newBindingContext);
        }

        return base.BindModel(controllerContext, bindingContext);
    }

    private FarmModel CreateFarmModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var farmsIds = new List<int>();

        var value = bindingContext.ValueProvider.GetValue("farmData");
        if(value != null && value.AttemptedValue != null)
        {
            var array = value.AttemptedValue.Split(new [] {','});
            foreach (var s in array)
            {
                int result;
                if(int.TryParse(s, out result))
                {
                    farmsIds.Add(result);
                }
            }
        }
        return new FarmModel() { FarmIds = farmsIds };
    }
}

<强>模型

public class FarmModel
{
    public IEnumerable<int> FarmIds { get; set; }
}

添加自定义活页夹

System.Web.Mvc.ModelBinders.Binders.Add(typeof(FarmModel), new FarmModelBinder());

答案 3 :(得分:1)

取自my answer

我将在这里向您展示一个我刚刚编写的非常简单的自定义模型绑定器(并在 .Net Core 2.0 中测试):

我的模型活页夹:

public class CustomModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        var value = valueProviderResult.FirstValue; // get the value as string

        var model = value.Split(",");
        bindingContext.Result = ModelBindingResult.Success(model);

        return Task.CompletedTask;
    }
}

我的模型(注意,只有一个属性有我的自定义模型活页夹注释):

public class CreatePostViewModel
{
    [Display(Name = nameof(ContentText))]
    [MinLength(10, ErrorMessage = ValidationErrors.MinLength)]
    public string ContentText { get; set; }

    [BindProperty(BinderType = typeof(CustomModelBinder))]
    public IEnumerable<string> Categories { get; set; } // <<<<<< THIS IS WHAT YOU ARE INTERESTER IN

    #region View Data
    public string PageTitle { get; set; }
    public string TitlePlaceHolder { get; set; }
    #endregion
}

它的作用是:它接收一些文本,例如&#34; aaa,bbb,ccc&#34;,并将其转换为数组,并将其返回到ViewModel。

我希望有所帮助。

免责声明:我不是模型粘合剂写作的专家,我在15分钟前就已经知道了,我找到了你的问题(没有有用的答案),所以我试着帮忙。这是一个非常基本的模型粘合剂,肯定需要一些改进。我学会了如何从official documentation页面编写它。

相关问题