如何使用AngularJS在我的http请求中发送参数?

Ala*_*an2 12 angularjs

我使用以下代码:

$http({
    method: 'GET',
    url: '/Admin/GetTestAccounts',
    data: { applicationId: 3 }
}).success(function (result) {
    $scope.testAccounts = result;
});
Run Code Online (Sandbox Code Playgroud)

代码将以下内容发送到我的服务器:

http://127.0.0.1:81/Admin/GetTestAccounts
Run Code Online (Sandbox Code Playgroud)

当我的MVC控制器接收到它时:

[HttpGet]
public virtual ActionResult GetTestAccounts(int applicationId)
{
    var testAccounts =
        (
            from testAccount in this._testAccountService.GetTestAccounts(applicationId)
            select new
            {
                Id = testAccount.TestAccountId,
                Name = testAccount.Name
            }
        ).ToList();

    return Json(testAccounts, JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)

它抱怨没有applicationId.

参数字典包含非可空类型'System.Int32'参数'applicationId'的空条目用于方法

有人可以解释为什么不将applicationId作为参数发送?以前我使用以下非Angular代码执行此操作并且它工作得很好:

$.ajax({
    url: '/Admin/GetTestAccounts',
    data: { applicationId: 3 },
    type: 'GET',
    success: function (data) {
        eViewModel.testAccounts(data);
    }
});
Run Code Online (Sandbox Code Playgroud)

Luc*_*nes 31

如果你不想使用jQuery的$ .param,你可以使用$ http的param字段来序列化一个对象.

var params = {
    applicationId: 3
}

$http({
    url: '/Admin/GetTestAccounts',
    method: 'GET',
    params: params
});
Run Code Online (Sandbox Code Playgroud)


dav*_*ekr 3

好的,我会尝试回答这个问题。

我认为问题在于 AngularJS 假定传递给 http 的数据将被 urlencoded。我不确定为什么 Angular 不会在存在对象时隐式序列化它。所以你必须自己编码:

 $http({
       method: 'GET',
       url: '/Admin/GetTestAccounts',
       data: 'applicationId=3'
       })
Run Code Online (Sandbox Code Playgroud)

或者使用 jQuery 参数为您编码:

$http({
     method: 'GET',
     url: '/Admin/GetTestAccounts',
     data: $.param({ applicationId: 3 })
     })
Run Code Online (Sandbox Code Playgroud)