【问题标题】:How to pass the javascript object from view to controller using angular JS?如何使用 Angular JS 将 javascript 对象从视图传递到控制器?
【发布时间】:2016-04-12 22:50:15
【问题描述】:

我尝试使用 angularJS $http 服务将客户类对象传递给 Asp.net MVC 控制器。

var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope,$http)
{   
    $scope.getRecord = function () {

        $scope.objCustomer = { Id: 5, Name: 'sasi', Dept: 'IT' };               
        $http({ url: "Home/GetCustbyID", 
                method: "GET", 
                params: {objCustomer: $scope.objCustomer} })
        .then(function (response) 
            {    
             //success code
            };});
}});

控制器动作定义如下:

public JsonResult GetCustbyID(Customer objCustomer)
{
   return Json(objCustomer, JsonRequestBehavior.AllowGet);
}

然而,在上面的控制器动作中,客户对象总是作为 null 传递的。我错过了什么吗?

请帮我解决这个问题。

【问题讨论】:

  • 如果你想在一个 JSON 对象中发送多个参数,你应该使用 POST 而不是 GET
  • 发布您的控制器“Home/GetCustbyID”代码。如果是通过 Id 获取,为什么需要 Name 和 Dept?
  • 感谢@Arkantos 的快速回复。是的 !!在我将其更改为 POST 方法后,它工作正常。谢谢:)

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


【解决方案1】:

当您实际向服务器发送数据时,您在$http 中发布。

var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope,$http)
{   
    $scope.getRecord = function () {

        $scope.objCustomer = { Id: 5, Name: 'sasi', Dept: 'IT' };               
        $http({ 
                url: "Home/GetCustbyID", 
                method: "POST", 
                data:  $.param({ objCustomer : $scope.objCustomer })                
              })
        .then(function(response) {    
             //success code
            };});
}});

在其他情况下,如果您想将数据作为 json 字符串发送/传递,则必须像这样使用stringify

 var data = $.param({
            json: JSON.stringify({
                name: $scope.name
            })
        });
 $http.post("/path_of_controller", data).success(function(data, status) {
           //do whatever you like
 })

【讨论】:

  • 是的..!您在上面发布的内容是正确的。在我将其更改为 POST 方法后,下面的代码对我有用。 $http({ url: "Home/GetCustbyID", method: "POST", data: { objCustomer: $scope.objCustomer} }).然后(函数(响应){});});但我使用了“数据”而不是 params 关键字。
【解决方案2】:

如果您希望在 AJAX 请求中的 JSON 对象中一次发送多个参数并将其捕获为服务器端的对象,则应使用 POST 请求。

$http.post(url, $scope.objCustomer)
     .then(successCallback, errorCallback); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-29
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    • 2018-01-01
    • 2017-03-31
    相关资源
    最近更新 更多