我使用带有“ GET”方法的ajax来获取DataTables数据,而我的ModelBinder仍然可以正常工作。在将方法更改为“ POST”之前,我的ModelBinder无法获得任何请求。
这是我的ModelBinder:
public class DataTableModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
var request = bindingContext.ActionContext.HttpContext.Request.Query;
// Retrieve request data
var draw = Convert.ToInt32(request["draw"]);
var start = Convert.ToInt32(request["start"]);
var length = Convert.ToInt32(request["length"]);
// Search
var search = new DataTableSearch
{
Value = request["search[value]"],
Regex = Convert.ToBoolean(request["search[regex]"])
};
// Order
var o = 0;
var order = new List<DataTableOrder>();
while (!string.IsNullOrEmpty(request["order[" + o + "][column]"]))
{
order.Add(new DataTableOrder
{
Column = Convert.ToInt32(request["order[" + o + "][column]"]),
Dir = request["order[" + o + "][dir]"]
});
o++;
}
// Columns
var c = 0;
var columns = new List<DataTableColumn>();
while (!string.IsNullOrEmpty(request["columns[" + c + "][name]"]))
{
columns.Add(new DataTableColumn
{
Data = request["columns[" + c + "][data]"],
Name = request["columns[" + c + "][name]"],
Orderable = Convert.ToBoolean(request["columns[" + c + "][orderable]"]),
Searchable = Convert.ToBoolean(request["columns[" + c + "][searchable]"]),
Search = new DataTableSearch
{
Value = request["columns[" + c + "][search][value]"],
Regex = Convert.ToBoolean(request["columns[" + c + "][search][regex]"])
}
});
c++;
}
var result = new DataTableRequest
{
Draw = draw,
Start = start,
Length = length,
Search = search,
Order = order.ToArray(),
Columns = columns.ToArray()
};
bindingContext.Result = ModelBindingResult.Success(result);
return Task.CompletedTask;
}
}
我真正想知道的是,如何从Model Binder中的ajax POST获取请求?
编辑:编辑时
var request = bindingContext.ActionContext.HttpContext.Request.Query;
到
Request.Form
我收到这样的错误:
'(((Microsoft.AspNetCore.Http.Internal.DefaultHttpRequest)((Microsoft.AspNetCore.Http.DefaultHttpContext)bindingContext.HttpContext).Request).Form'引发了类型为'System.InvalidOperationException'的异常
对不起,我的英语。预先感谢
编辑:
没关系。我解决了这个问题,我只需要在我的Controller参数中放入[FromForm]
。然后使用Request.Form
来获取请求。我从数据表ajax发送