我正在使用远程加载数据的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)
但排序始终为空。有谁知道我怎么能做到这一点?
我可以回退到Request.QueryString使用,但这有点像kludge。
var field = Request.QueryString["sort[0][field]"];
var dir = Request.QueryString["sort[0][dir]"];
答案 0 :(得分: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());
答案 1 :(得分:0)
对于asp.net核心,我没有使用模型绑定器,因为数据是作为字典发送的,所以我只在api上使用了以下方法签名,绑定自动发生(客户端不需要参数映射)>
public async Task<JsonResult> GetAccessions(.., IDictionary<string, string>[] sort)
{
...
}