首页 > 解决方案 > 将 Json 数据从 Angularjs 发布到 MVC 控制器

问题描述

当我将 JSON 数据从 AngularJS 传递到 MVC 时。我得到以下错误。

Http 请求配置 url 必须是字符串或 $sce 可信对象。收到:{"method":"POST","url":"Home/SavePDDetails","datatype":"json","data":{"PD":{"Name":"qqq","Address" :“万维网”}}}

MVC 代码:

[HttpPost]
public JsonResult SavePDDetails(PDDetailsDTO PD)
{
    new PDDetailsDAL().SavePDDetails(PD);
    return Json(new { Success = true, Message = "Success" });
}

AngularJS 代码

$scope.Click = function() {
  console.log('clicked');

  $http.post({
    method: 'POST',
    url: 'Home/SavePDDetails',
    datatype: "json",
    data: {
      PD: $scope.PD
    }
  }).success(function(response) {
      console.log('success');
      console.log(response);
  }).error(function(response) {
      console.log('error');
      console.log(response);
  });
}

标签: angularjsjsonasp.net-mvc-5

解决方案


If data and url are passed as a properties of the config object, don't use the $http.post method. Simply use $http:

  ̶$̶h̶t̶t̶p̶.̶p̶o̶s̶t̶(̶{̶
  $http({
    method: 'POST',
    url: 'Home/SavePDDetails',
    ̶d̶a̶t̶a̶t̶y̶p̶e̶:̶ ̶"̶j̶s̶o̶n̶"̶,̶
    data: {
      PD: $scope.PD
    }
  })

There is no need to stringify the data as the $http Service does that automatically.


推荐阅读