将json对象传递给mvc4控制器 - 作为Nothing传递的数组

时间:2015-06-25 17:10:00

标签: javascript json asp.net-mvc-4

我搜索过并发现了不少结果,但似乎都没有。我可以看到params.list数组中有值(如下面的console.log所示),但在控制器中,ZoneDataList是" Nothing"虽然vm.farmId,vm.cropPlanId和vm.taskId在Controller中有数据。

我做错了什么?

这是我的代码: 使用Javascript:

var zonedataArray = [];
    var zoneInfo = {};
    var params = { farmId: localStorage.FarmId, cropPlanId: selectedCrpPlanId, taskId: taskId, list: [] };

    for (i = 0; i < viewModel.nutZoneRows().length; i++) {
      zoneInfo = { "Rate": viewModel.nutZoneRows()[i].Rate(), "TotalAmount": viewModel.nutZoneRows()[i].TotalAmount() };
      zonedataArray.push(zoneInfo);
      params.list.push(zoneInfo);
    }

    for (i = 0; i < params.list.length; i++) {
      console.log("params.list[i].Rate: " + params.list[i].Rate);
    }//has correct values

    $.ajax({
      contentType: 'application/json',
      url: '@Url.Action("SaveNutritionTask", "CropPlans")',
      type: "POST",
      dataType: "json",
      data: JSON.stringify(params),
      traditional: true,
      success: function (result) {
        $.mobile.loading('hide');
      },
      error: function (xhr, ajaxOptions, thrownError) {
        $.mobile.loading('hide');
      } //error

    }); //ajax
  }; //self.SaveCropPlan

控制器方法:

<HttpPost()>
Public Function SaveNutritionTask(vm As CropPlanModel.CompleteZoneData) As JsonResult

End Function

型号:

Public Class CompleteZoneData
  Public Property farmId As Guid
  Public Property cropPlanId As Guid
  Public Property taskId As Guid
  Public Property ZoneDataList As List(Of ZoneData)
End Class

Public Class ZoneData
  Public Property Rate As String
  Public Property TotalAmount As String
End Class

2 个答案:

答案 0 :(得分:0)

您可能需要使用模型绑定属性来绑定json(这是您可能需要转换为VB的c#实现)

   public class FromJsonAttribute : CustomModelBinderAttribute
   {
         private readonly static JavaScriptSerializer serializer = new JavaScriptSerializer();
         public override IModelBinder GetBinder()
         {
     return new JsonModelBinder();
  }

  private class JsonModelBinder : IModelBinder
  {
     public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
     {
       var stringified = controllerContext.HttpContext.Request[bindingContext.ModelName];
       if (string.IsNullOrEmpty(stringified))
            return null;
       return serializer.Deserialize(stringified, bindingContext.ModelType);
      }
 }

}

并修改您的控制器功能,如

       <HttpPost()>
       Public Function SaveNutritionTask([FromJson]vm As CropPlanModel.CompleteZoneData) As JsonResult

       End Function

答案 1 :(得分:0)

发现问题。应该将javascript代码中的params列表重命名为ZoneDataList以匹配Class名称。