jquery – MVC3 Json模型绑定在发送到服务器时不起作用

前端之家收集整理的这篇文章主要介绍了jquery – MVC3 Json模型绑定在发送到服务器时不起作用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我对MVC3和模型绑定有一个奇怪的问题.
当我将JSON对象发布到我的控制器时,模型绑定器根本无法创建一个类型化的对象.所有属性都是默认属性(即空字符串)

但是,如果我在服务器上创建实例,并将其作为JSON操作结果发送,则线上的数据看起来相同.

我试过了

  1. $.ajaxSettings.traditional = true;

它没有任何区别

作为一个例子,如果我发布

  1. {"RoutineName":"My new routine","Routines":[{"DayName":"Monday","Items":[21,31]}]}

模型绑定器失败,但来自服务器的数据看起来像

  1. {"RoutineName":"Routine From Code","Items":[1,2]},{"DayName":"Tuesday","Items":[]}]}

用于生成内容的html看起来像

  1. $('#submitRoutine').click(function () {
  2. var routines = [];
  3. $('.DayName').each(function (index,item) {
  4. var $item = $(item);
  5. var name = $item.html();
  6. var routineItems = [];
  7. $($item.attr('href')).find('.itemId').each(function () {
  8. routineItems.push(parseInt($(this).val(),10));
  9. });
  10. routines.push({
  11. DayName: name,Items: routineItems
  12. });
  13. });
  14. var routine = {
  15. RoutineName: $('#routineName').val(),Routines: routines
  16. };
  17. $.ajaxSettings.traditional = true;
  18. $.post('/Machine/CreateRoutine',JSON.stringify(routine),function (data) {},'json');
  19. });

所以看起来从类型化对象到JSON的模型绑定是可以的,但是以另一种方式返回则不行.有没有我错过的东西?

模型在F#中

  1. type RoutineDayviewmodel() =
  2. let mutable _name = String.Empty
  3. let mutable _items = new ResizeArrayviewmodel() =
  4. let mutable _name = String.Empty
  5. let mutable _routines = new ResizeArrayviewmodel>()
  6. member x.RoutineName with get() = _name and set value = _name <- value
  7. member x.Routines with get() = _routines and set value = _routines <- value

编辑:
我也尝试过以下C#类并获得相同的结果

  1. public class RoutineDayviewmodel
  2. {
  3. public string DayName { get; set; }
  4. public Listviewmodel
  5. {
  6. public string RoutineName { get; set; }
  7. public Listviewmodel> Routines { get; set; }
  8. }

我还在global.asax中添加了以下内容

  1. ValueProviderFactories.Factories.Add(new JsonValueProviderFactory())

谢谢

最佳答案
如果您打算发送JSON格式的请求,则需要将请求内容类型设置为application / json,这是您使用JSON.stringify方法执行的操作.所以代替:

  1. $.post('/Machine/CreateRoutine','json');

你可以使用:

  1. $.ajax({
  2. url: '/Machine/CreateRoutine',type: 'POST',contentType: 'application/json; charset=utf-8',data: JSON.stringify(routine),success: function (data) {
  3. }
  4. });

有了这个,您不需要设置$.ajaxSettings.traditional,也不应该在Global.asax中添加任何JsonValueProviderFactory,因为ASP.NET MVC 3中默认添加了此提供程序.

猜你在找的jQuery相关文章