我对MVC3和模型绑定有一个奇怪的问题.
当我将JSON对象发布到我的控制器时,模型绑定器根本无法创建一个类型化的对象.所有属性都是默认属性(即空字符串)
但是,如果我在服务器上创建实例,并将其作为JSON操作结果发送,则线上的数据看起来相同.
我试过了
$.ajaxSettings.traditional = true;
它没有任何区别
作为一个例子,如果我发布
{"RoutineName":"My new routine","Routines":[{"DayName":"Monday","Items":[21,31]}]}
模型绑定器失败,但来自服务器的数据看起来像
{"RoutineName":"Routine From Code","Items":[1,2]},{"DayName":"Tuesday","Items":[]}]}
$('#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 ResizeArrayviewmodel() =
let mutable _name = String.Empty
let mutable _routines = new ResizeArrayviewmodel>()
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 Listviewmodel
{
public string RoutineName { get; set; }
public Listviewmodel> Routines { get; set; }
}
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory())
谢谢
最佳答案
如果您打算发送JSON格式的请求,则需要将请求内容类型设置为application / json,这是您使用JSON.stringify方法执行的操作.所以代替:
原文链接:https://www.f2er.com/jquery/428573.html$.post('/Machine/CreateRoutine','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中默认添加了此提供程序.