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

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

本文介绍了模型绑定逗号分隔查询字符串参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何绑定逗号分隔值的查询字符串参数

How can I bind query string parameter that is comma separated value

http://localhost/Action?ids=4783,5063,5305

到需要列表的控制器操作?

to a controller action expecting a list?

public ActionResult Action(List<long> ids)
{
    return View();
}

注意! ids 在控制器动作中必须是一个列表(或基于 IEnumerable 的东西),所以 string ids 不被接受作为答案因为这些参数会传递给许多操作,将字符串解析为数组会增加不必要的噪音.

Note! ids in the controller action must a list (or something IEnumerable based), so string ids is not accepted as an answer because these parameters are passed to many actions and parsing string to an array would add unwanted noise.

推荐答案

Archils 的回答给出了一些如何实现我自己的模型绑定器的想法.我能够稍微简化源代码,因为不需要非常通用的 CSV 支持.我没有将接收到的数据设置为 List,而是将其放入类中.

Archils answer gave some ideas how to implement my own model binder. I was able to slightly simplify the source code as there wasn't need for very generic CSV support. Instead of setting the received data to List<int> I am putting it to the class.

模型绑定器

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

这篇关于模型绑定逗号分隔查询字符串参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 22:12