Dyl*_*lan 5 jquery json asp.net-mvc-3
我对MVC3和模型绑定有一个奇怪的问题.当我将JSON对象发布到我的控制器时,模型绑定器根本无法创建一个类型化的对象.所有属性都是默认属性(即空字符串)
但是,如果我在服务器上创建实例,并将其作为JSON操作结果发送,则线上的数据看起来相同.
我试过了
$.ajaxSettings.traditional = true;
Run Code Online (Sandbox Code Playgroud)
它没有任何区别
作为一个例子,如果我发布
{"RoutineName":"My new routine","Routines":[{"DayName":"Monday","Items":[21,31]}]}
Run Code Online (Sandbox Code Playgroud)
模型绑定器失败,但来自服务器的数据看起来像
{"RoutineName":"Routine From Code","Routines":[{"DayName":"Monday","Items":[1,2]},{"DayName":"Tuesday","Items":[]}]}
Run Code Online (Sandbox Code Playgroud)
用于生成此内容的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');
});
Run Code Online (Sandbox Code Playgroud)
所以看起来从类型化对象到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
Run Code Online (Sandbox Code Playgroud)
编辑:我也试过以下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; }
}
Run Code Online (Sandbox Code Playgroud)
我还在global.asax中添加了以下内容
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory())
Run Code Online (Sandbox Code Playgroud)
谢谢
application/json如果您打算发送JSON格式的请求,则需要将请求内容类型设置为您正在使用该JSON.stringify方法执行的操作.所以代替:
$.post('/Machine/CreateRoutine', JSON.stringify(routine),function (data) {},'json');
Run Code Online (Sandbox Code Playgroud)
你可以使用:
$.ajax({
url: '/Machine/CreateRoutine',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(routine),
success: function (data) {
}
});
Run Code Online (Sandbox Code Playgroud)
有了这个,您不需要设置$.ajaxSettings.traditional也不应该JsonValueProviderFactory在Global.asax中添加任何内容,因为ASP.NET MVC 3中默认添加了此提供程序.
| 归档时间: |
|
| 查看次数: |
3220 次 |
| 最近记录: |