集成ASP.NET Webforms,WebAPI和AngularJS

时间:2022-04-18 13:43:45

I'm trying to get my first ASP.NET Webforms and AngularJS app up and running, but I'm struggling...

我正在尝试启动和运行我的第一个ASP.NET Webforms和AngularJS应用程序,但我正在努力......

I created a blank, new ASP.NET 4.5.1 webforms app, and included WebAPI into the mix. I created a sample page for my list of customers, and a standard, EF6-based WebAPI CustomerController : ApiController with all the usual CRUD methods. I tested that WebAPI using Fiddler and low and behold - I get my 8 customers back from my database.

我创建了一个空白的,新的ASP.NET 4.5.1 webforms应用程序,并将WebAPI包含在其中。我为我的客户列表创建了一个示例页面,以及一个基于EF6的标准WebAPI CustomerController:ApiController以及所有常用的CRUD方法。我使用Fiddler测试了那个WebAPI并且看得很低 - 我从我的数据库中找回了我的8个客户。

Getting this into AngularJS however has been a bit of a unsuccessful and highly frustrating experience ....

然而,进入AngularJS一直是一个不成功和非常令人沮丧的经历....

I included AngularJS from NuGet and that seems to have worked - no errors shown or anything, a pile of angular*.js files dumped into my Scripts folder.

我从NuGet中包含AngularJS,这似乎有效 - 没有显示任何错误或任何东西,一堆有角度的* .js文件被转储到我的Scripts文件夹中。

I created a basic CustomerList.aspx page based on a master page which includes the <html lang="en" ng-app="TestAngular"> tag.

我基于包含标记的母版页创建了一个基本的CustomerList.aspx页面。

In order to get the data from the WebAPI service, I created my Angular module, and created a model inside the $scope, and created a service to fetch the data from the WebAPI:

为了从WebAPI服务获取数据,我创建了我的Angular模块,并在$ scope内创建了一个模型,并创建了一个服务来从WebAPI获取数据:

Inside app.js:

var testModule = angular.module('TestAngular', [ ]);

testModule.controller('clientController', function ($scope, clientService) {
    $scope.model = [];
    clientService.getAllClients(function(results) {
        $scope.model.clients = results;
    });

    $scope.model.clientCount = $scope.model.clients.count;
});

testModule.factory('clientService', function ($http) {
    var srv = {};
    srv._baseUrl = 'http://localhost:56313';

    // Public API
    return {
        getAllClients: function(callback) {
            return $http.get(srv._baseUrl + '/api/Customer').success(callback);
        }
    };
});

From what limited Javascript understanding I have, this should define a clientService (the testModule.factory() call) that calls my WebAPI URL, gets the JSON back, and the callback function then stuffs those customers retrieved into the $scope.model.clients property, and the $scope.model.clientCount should also be calculated.

从我有限的Javascript理解,这应该定义一个clientService(testModule.factory()调用),它调用我的WebAPI URL,获取JSON,然后回调函数将检索到的客户填充到$ scope.model.clients属性,还应计算$ scope.model.clientCount。

My ASPX page looks something like this:

我的ASPX页面看起来像这样:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CustomerList.aspx.cs" Inherits="TestAngular.CustomerList" MasterPageFile="~/Site.Master"  %>

<asp:Content runat="server" ID="content" ContentPlaceHolderID="MainContent">
    <h2>My customers</h2>

    <div class="panel panel-default" data-ng-controller="clientController">
        We have a total of {{ model.clientCount }} clients in our database table ...

        <div class="list-group" data-ng-repeat="client in model.clients">
            <div class="list-group-item">
                <span>{{ client.Name }}</span><br/>
                <span>{{ client.Name2 }}</span><br/>
            </div>     
        </div>
    </div>
</asp:Content>

So the <div> with the data-ng-controller should "connect" that DIV with the AngularJS controller, should load the customers from the WebAPI call, and contain them in the model, which would then be rendered to the ASPX page using the data binding syntax ({{ client.Name }} etc.)

因此,带有data-ng-controller的

应该将DIV与AngularJS控制器“连接”,应该从WebAPI调用加载客户,并将它们包含在模型中,然后使用该模型将其呈现给ASPX页面。数据绑定语法({{client.Name}}等)

Trouble is: the call to the WebAPI happens and the correct 8 customers are returned, however, when I debug into the Javascript code, the clientCount is always undefined and the ASPX page only shows two empty rows which probably would correspond to customers that have been retrieved - but why only 2, not 8 ??

问题是:调用WebAPI并返回正确的8个客户,但是,当我调试Javascript代码时,clientCount始终未定义,ASPX页面只显示两个空行,这些行可能对应于已经存在的客户检索 - 但为什么只有2,而不是8?

I'm totally lost and stuck - can anyone spot what I'm doing wrong, what I'm missing here??

我完全迷失了方向 - 有人能发现我做错了什么,我在这里缺少什么?

1 个解决方案

#1


3  

You are definately on the right track. At the moment, the problem is down to the clientService getAllClients method.

你肯定是在正确的轨道上。目前,问题在于clientService getAllClients方法。

You should return the promise and then the data will chain through to the controller:

您应该返回承诺,然后数据将链接到控制器:

getAllClients: function(callback) {
    return $http.get(srv._baseUrl + '/api/Customer').success(callback);
}

You may also want to take a look at the count line:

您可能还想查看计数行:

$scope.model.clientCount = $scope.model.clients.count;

Before the promise is resolved (and the callback is invoked), $scope.model.clients will be undefined. So, I'd expect this line to fail. Also, to get the count of an array, you need length.

在解析promise之前(并且调用了回调),$ scope.model.clients将是未定义的。所以,我希望这条线路失败。另外,要获得数组的计数,您需要长度。

You should set the clientCount inside of the callback:

您应该在回调中设置clientCount:

clientService.getAllClients(function(results) {
    $scope.model.clients = results;
    $scope.model.clientCount = $scope.model.clients.length;
});

Edit:

Typically, it is favoured to use the promise returned by $http. So, the controller would slightly change to:

通常,使用$ http返回的promise是有利的。因此,控制器会略微改为:

clientService.getAllClients().then(function(response) {
    $scope.model.clients = response.results;
    $scope.model.clientCount = response.results.length;
});

And then the service would change to:

然后服务将变为:

getAllClients: function() {
    return $http.get(srv._baseUrl + '/api/Customer');
}

Angular uses promises from $q instead of callbacks (for most apis). They make chaining and exception handling much easier.

Angular使用来自$ q的承诺而不是回调(对于大多数apis)。它们使链接和异常处理变得更加容易。

Also, since, in this case, you know you are handling a promise from $http, you can use the success method in the controller as well:

此外,因为在这种情况下,您知道您正在处理$ http的承诺,您也可以使用控制器中的success方法:

clientService.getAllClients().success(function(results) {
    $scope.model.clients = results;
    $scope.model.clientCount = results.length;
});

success unwraps the response and sends only the body through to the callback.

成功展开响应并仅将正文发送到回调。

#1


3  

You are definately on the right track. At the moment, the problem is down to the clientService getAllClients method.

你肯定是在正确的轨道上。目前,问题在于clientService getAllClients方法。

You should return the promise and then the data will chain through to the controller:

您应该返回承诺,然后数据将链接到控制器:

getAllClients: function(callback) {
    return $http.get(srv._baseUrl + '/api/Customer').success(callback);
}

You may also want to take a look at the count line:

您可能还想查看计数行:

$scope.model.clientCount = $scope.model.clients.count;

Before the promise is resolved (and the callback is invoked), $scope.model.clients will be undefined. So, I'd expect this line to fail. Also, to get the count of an array, you need length.

在解析promise之前(并且调用了回调),$ scope.model.clients将是未定义的。所以,我希望这条线路失败。另外,要获得数组的计数,您需要长度。

You should set the clientCount inside of the callback:

您应该在回调中设置clientCount:

clientService.getAllClients(function(results) {
    $scope.model.clients = results;
    $scope.model.clientCount = $scope.model.clients.length;
});

Edit:

Typically, it is favoured to use the promise returned by $http. So, the controller would slightly change to:

通常,使用$ http返回的promise是有利的。因此,控制器会略微改为:

clientService.getAllClients().then(function(response) {
    $scope.model.clients = response.results;
    $scope.model.clientCount = response.results.length;
});

And then the service would change to:

然后服务将变为:

getAllClients: function() {
    return $http.get(srv._baseUrl + '/api/Customer');
}

Angular uses promises from $q instead of callbacks (for most apis). They make chaining and exception handling much easier.

Angular使用来自$ q的承诺而不是回调(对于大多数apis)。它们使链接和异常处理变得更加容易。

Also, since, in this case, you know you are handling a promise from $http, you can use the success method in the controller as well:

此外,因为在这种情况下,您知道您正在处理$ http的承诺,您也可以使用控制器中的success方法:

clientService.getAllClients().success(function(results) {
    $scope.model.clients = results;
    $scope.model.clientCount = results.length;
});

success unwraps the response and sends only the body through to the callback.

成功展开响应并仅将正文发送到回调。