Вы можете использовать IDictionary<string, object>
в качестве аргумента действия.Просто напишите пользовательский механизм связывания модели, который будет анализировать в нем запрос JSON:
public class DictionaryModelBinder : IModelBinder
{
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;
}
return new JavaScriptSerializer().DeserializeObject(json);
}
}
}
, который будет зарегистрирован в Application_Start
:
ModelBinders.Binders.Add(typeof(IDictionary<string, object>), new DictionaryModelBinder());
, тогда вы можете выполнить следующее действие контроллера:
[HttpPost]
public ActionResult Foo(IDictionary<string, object> model)
{
return Json(model);
}
, в который вы можете бросить все, что угодно:
var model = {
foo: {
bar: [ 1, 2, 3 ],
baz: 'some baz value'
}
};
$.ajax({
url: '@Url.Action("foo")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(model),
success: function (result) {
// TODO: process the results from the server
}
});