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

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

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

问题描述

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

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的),所以字符串ID 不被接受作为回答。

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答案提出了一些想法如何实现自己的模型粘合剂。我能够稍微简化了源$ C ​​$ C,因为没有需要非常通用的CSV支持。相反,接收到的数据设置为列表与LT的; INT方式&gt; 我把它的类

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-18 22:31