【问题标题】:Bind a QueryString that has arrays with MVC使用 MVC 绑定具有数组的 QueryString
【发布时间】:2012-03-04 18:52:47
【问题描述】:

我正在使用远程加载数据的 Telerk Kendo UI 网格。传递给我的操作方法的QueryString 如下所示:-

take=10&skip=0&page=1&pageSize=10&sort[0][field]=value&sort[0][dir]=asc

我正在研究如何将sort 参数绑定到我的方法中?是否有可能或者我需要手动枚举QueryString 集合或创建自定义活页夹?

到目前为止,我已经尝试过:-

public JsonResult GetAllContent(int page, int take, int pageSize, string[] sort)

public JsonResult GetAllContent(int page, int take, int pageSize, string sort)

但 sort 始终为空。有谁知道我如何做到这一点?

我可以回退到 Request.QueryString 使用,但这有点麻烦。

var field = Request.QueryString["sort[0][field]"];
var dir = Request.QueryString["sort[0][dir]"];

【问题讨论】:

    标签: asp.net-mvc kendo-ui


    【解决方案1】:

    您可以使用字典数组:

    public ActionResult Index(
        int page, int take, int pageSize, IDictionary<string, string>[] sort
    )
    {
        sort[0]["field"] will equal "value"
        sort[0]["dir"] will equal "asc"
        ...
    }
    

    然后定义一个自定义模型绑定器:

    public class SortViewModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var modelName = bindingContext.ModelName;
            var keys = controllerContext
                .HttpContext
                .Request
                .Params
                .Keys
                .OfType<string>()
                .Where(key => key.StartsWith(modelName));
    
            var result = new Dictionary<string, string>();
            foreach (var key in keys)
            {
                var val = bindingContext.ValueProvider.GetValue(key);
                result[key.Replace(modelName, "").Replace("[", "").Replace("]", "")] = val.AttemptedValue;
            }
    
            return result;
        }
    }
    

    将在 Global.asax 中注册:

    ModelBinders.Binders.Add(typeof(IDictionary<string, string>), new SortViewModelBinder());
    

    【讨论】:

    • 感谢 Darin,这是我喜欢 Stack Overflow 的原因之一。
    • 使用 IDictionary 数组来捕获排序标准是我目前在网上找到的最干净的实现。谢谢。
    【解决方案2】:

    对于 asp.net 核心,我没有使用模型绑定器,因为数据是作为字典发送的,我只是在我的 api 上使用了以下方法签名,并且绑定自动发生(客户端不需要参数映射)

    public async Task<JsonResult> GetAccessions(.., IDictionary<string, string>[] sort)
    {
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-03
      • 2012-12-27
      • 1970-01-01
      • 1970-01-01
      • 2014-07-08
      • 1970-01-01
      相关资源
      最近更新 更多