我对MVC3和模型绑定有一个奇怪的问题。 当我将JSON对象发布到我的控制器时,模型绑定器根本无法创建一个类型化的对象。所有属性都是默认属性(即空字符串)
但是,如果我在服务器上创建实例,并将其作为JSON操作结果发送,则线上的数据看起来完全相同。
我已经尝试了
$.ajaxSettings.traditional = true;
并没有区别
作为一个例子,如果我发布
{"RoutineName":"My new routine","Routines":[{"DayName":"Monday","Items":[21,31]}]}
模型绑定器失败,但来自服务器的数据看起来像
{"RoutineName":"Routine From Code","Routines":[{"DayName":"Monday","Items":[1,2]},{"DayName":"Tuesday","Items":[]}]}
用于生成此内容的html类似于
$('#submitRoutine').click(function () {
var routines = [];
$('.DayName').each(function (index, item) {
var $item = $(item);
var name = $item.html();
var routineItems = [];
$($item.attr('href')).find('.itemId').each(function () {
routineItems.push(parseInt($(this).val(), 10));
});
routines.push({
DayName: name,
Items: routineItems
});
});
var routine = {
RoutineName: $('#routineName').val(),
Routines: routines
};
$.ajaxSettings.traditional = true;
$.post('/Machine/CreateRoutine', JSON.stringify(routine),function (data) {},'json');
});
所以看起来从类型化对象到JSON的模型绑定是可以的,但是从另一个方面回来并不是。有没有我错过的东西?
模型位于F#
type RoutineDayViewModel() =
let mutable _name = String.Empty
let mutable _items = new ResizeArray<int>()
member x.DayName with get() = _name and set value = _name <- value
member x.Items with get() = _items and set value = _items <- value
type RoutineViewModel() =
let mutable _name = String.Empty
let mutable _routines = new ResizeArray<RoutineDayViewModel>()
member x.RoutineName with get() = _name and set value = _name <- value
member x.Routines with get() = _routines and set value = _routines <- value
编辑: 我也尝试过以下C#类并获得相同的结果
public class RoutineDayViewModel
{
public string DayName { get; set; }
public List<int> Items{ get; set; }
}
public class RoutineViewModel
{
public string RoutineName { get; set; }
public List<RoutineDayViewModel> Routines { get; set; }
}
我还在global.asax
中添加了以下内容ValueProviderFactories.Factories.Add(new JsonValueProviderFactory())
由于
答案 0 :(得分:8)
如果您打算发送JSON格式的请求,则需要将请求内容类型设置为application/json
,这是您使用JSON.stringify
方法执行的操作。所以而不是:
$.post('/Machine/CreateRoutine', JSON.stringify(routine),function (data) {},'json');
你可以使用:
$.ajax({
url: '/Machine/CreateRoutine',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(routine),
success: function (data) {
}
});
使用此功能,您无需设置$.ajaxSettings.traditional
,也不应在Global.asax中添加任何JsonValueProviderFactory
,因为ASP.NET MVC 3中已默认添加此提供程序。
答案 1 :(得分:2)
我使用Nick Riggs Postify javascript代码
解决了这个问题http://www.nickriggs.com/posts/post-complex-javascript-objects-to-asp-net-mvc-controllers/