【问题标题】:Passing and retrieving complex objects from Angularjs to Web Api将复杂对象从 Angularjs 传递和检索到 Web Api
【发布时间】:2016-01-16 07:35:10
【问题描述】:

我有一个 Angular 表单,用户在其中输入各种条件,然后我想将这些条件传递给 Web Api 并在运行查询后得到结果。我最初认为这是一个“获取”,但在将复杂对象传递给 Web Api 时遇到了麻烦。有了一些建议,然后我使用了 Post 并能够通过条件在 Web Api 中运行查询,但我无法在 Angular 中返回结果。运行 Web Api 方法并获取结果。但我在数据服务中看不到结果。

当查询条件是多个字段并且一些是列表时,最好的方法是什么?我找不到任何好的例子。

这里是Web Api方法:

[HttpPost] 公共 IEnumerable 帖子([FromBody]FrequentPawnerReportCriteria 标准) { var repo = new FrequentPawnerReport(); var 结果 = repo.GetReport(标准); 返回结果; }`

这里是数据服务:

function getFrequentPawner(criteria) {
            return $http.post("/api/FrequentPawner/Post", criteria)
                .then (getFrequentPawnerComplete)
                .catch(getFrequentPawnerFailed);
            function getFrequentPawnerComplete(response) {
                var x = response
                return response.data.results;
            }
            function getFrequentPawnerFailed(error) {
                alert("XHR failed for frequent pawner report: " + error.responseText);
            }
        }

这是控制器代码:

function getTopPawnerResults(criteria) {

            return DataContext.getFrequentPawner(criteria)
                .then(
                function (result) {
                    vm.frequentPawnerReport = result.data;

                    return vm.frequentPawnerReport;
                });
        }

【问题讨论】:

  • 请显示代码,概述您到目前为止所尝试的内容。如果您为了清晰起见添加代码,用户将更有可能为您提供帮助。
  • 使用 post 或 get 不应基于“我最初认为这是一个“Get”,但在将复杂对象传递给 Web Api 时遇到了麻烦”
  • 实在不清楚具体是什么问题。来自服务器的响应不应该是 get 或 post 的问题
  • 我添加了我正在处理的代码。

标签: angularjs asp.net-web-api2


【解决方案1】:

只需使用 JSON。使用 JSON.stringify() 将 JSON 对象解析为字符串并发布它。同样,从服务器返回 JSON 字符串,并将其分配给 Angular 中的变量。它会自动转换为 JSON 对象。

【讨论】:

    【解决方案2】:

    我认为,当您发出发布请求时,您需要有一个回调函数,当您的 Web Api 返回时会调用该回调函数。在该回调函数中,您可以更新您的 $scope 变量,这将使您的 web ui 显示来自服务器的响应。你可以在这里找到我的意思的一个例子:https://docs.angularjs.org/api/ng/service/$http

    它的要点: $http({ method: 'POST', url: '/path/to/your/web/api', function(success) { console.log('Successfully executed the api call'); $scope.response = response; // change this to match the data you are expecting from the server response }, function(failure) { console.error('There was an error'); $scope.failure = failure; // change this to match your failure response } );

    【讨论】:

      【解决方案3】:

      感谢您的回复。该项目是 Web 表单和 angularjs 的混合体。我正在迁移应用程序,但没有注意到此表单存在冲突,导致回发并使其看起来好像没有返回结果。我将表格放入一个单独的项目中,并且能够得到我想要的结果。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-12
        • 2023-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-12
        相关资源
        最近更新 更多