2012-03-04 26 views
5

我正在使用遠程加載數據的Telerk Kendo UI網格。傳遞到我的行動方法QueryString看起來是這樣的: -綁定具有MVC數組的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) 

但排序總是空。有誰知道我能做到這一點?

我可以回退到Request.QueryString使用,但這是一個kludge位。

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

回答

7

你可以使用詞典的數組:

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

謝謝Darin,這是我的原因之一ve堆棧溢出。 – Rippo 2012-03-04 20:50:23

+0

使用IDictionary數組捕獲排序標準是迄今爲止我在網上找到的最乾淨的實現。謝謝。 – YYL 2012-11-14 19:22:32