如何通过 AJAX
调用将 动态
数据传递给 MVC
Controller
?
Controller
:
public JsonResult ApplyFilters(dynamic filters){
return null;
}
AJAX
调用:
$(':checkbox').click(function (event) {
var serviceIds = $('input[type="checkbox"]:checked').map(function () {
return $(this).val();
}).toArray();
//alert(serviceIds);
$.ajax({
type: 'GET',
url: '/home/ApplyFilters',
data: JSON.stringify({
name: serviceIds
}),
contentType: 'application/json',
success: function (data) {
alert("succeeded");
},
error: function (err, data) {
alert("Error " + err.responseText);
}
});
//return false;
});
理想情况下,filters
将包含 serviceIds
作为属性
例如:filters.ServiceIds
。
我得到了另一个用于日期范围的过滤器,并且会像这样添加一个过滤器:filters.DateRange
。
服务器端在 ApplyFilters()
dynamic
对象获取
最佳答案
据我所知default ASP MVC模型绑定(bind)器无法完成这样的事情。
幸运的是,有很多解决方案,这里有两个:
1。 Here是第一个,它将您的 JSON 数据转换为 IDictionary<string, object>
在将实例传递给您的 Controller 操作之前。你最终会得到:
public JsonResult ApplyFilters(IDictionary<string, object> filters)
{
return null;
}
2。 second approach使您的 Controller 操作能够接收 JsonValue实例。让你的 Action 看起来像这样:
public JsonResult ApplyFilters([DynamicJson]JsonValue filters)
{
return null;
}
3。根据前面的教程,您可以创建自己的自定义模型绑定(bind)器,返回一个动态对象。以下代码取自第一个提案并经过修改以生成动态对象。这只是为了说明这个想法,不要按原样使用它:
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
{
return null;
}
controllerContext.HttpContext.Request.InputStream.Position = 0;
using (var reader = new StreamReader(controllerContext.HttpContext.Request.InputStream))
{
var json = reader.ReadToEnd();
if (string.IsNullOrEmpty(json))
{
return null;
}
dynamic result = new ExpandoObject();
var deserializedObject = new JavaScriptSerializer().DeserializeObject(json) as IDictionary<string, object>;
if (deserializedObject != null)
{
foreach (var item in deserializedObject)
{
((IDictionary<string, object>)result).Add(item.Key, item.Value);
}
}
return result;
}
}
这些解决方案依赖于构建自定义模型绑定(bind)器来处理这种特殊情况:
- 自定义模型 Binder 只是 IModelBinder 的一个实现负责解析 JSON 发布数据并将其转换为另一种格式的接口(interface)。
- 通过注册(使用
ModelBinders.Binders.Add
或使用专用属性 (CustomModelBinderAttribute))告诉 ASP MVC 框架使用这些特定的自定义模型绑定(bind)器。
关于c# - 使用 AJAX 将动态数据传递给 mvc Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19616406/