简体   繁体   中英

Angular Routing for Single Page Application (ASP.Net MVC Web API)

  1. User is presented with a list of companies
  2. User selects a company, and is presented with a list of reports defined for that company

I have configured my angular appp as such:

angular.module('xcmApp', ['ngRoute', 'ngResource'])
.config(function ($routeProvider) {
    $routeProvider
    .when('/',
    {
        controller: 'companiesController',
        templateUrl: '/views/companylist.html'
    })
    .when('/Reports/:companyid',
    {
        controller: 'reportsController',
        templateUrl: 'views/reportlist.html'
    })
    .otherwise({ redirectTo: '/' })
})
.factory('companiesFactory', ['$resource',
    function ($resource) {
        return $resource('/api/companies', {}, {
            query: { method: 'GET', params: {}, isArray: true }
        });
    }
])
.controller('companiesController', function ($scope, companiesFactory) {
    $scope.Companies = companiesFactory.query();
})
.factory('reportsFactory', ['$resource',
    function ($resource) {
        return $resource('/api/reports/:companyid', {}, {
            query: { method: 'GET', params: { companyid: '@@companyid' }, isArray: true }
        });
    }
])
.controller('reportsController', function ($scope, reportsFactory) {
    $scope.Reports = reportsFactory.query();
});

My WebAPI Controller is simple:

[Route("api/[controller]")]
public class ReportsController : Controller
{
    // GET: api/values
    [HttpGet("{companyid}")]
    public IEnumerable<PBMMMIS.Data.WebReport> Get(string companyid)
    {
        return Xerox.XCM.PBMMMIS.Data.CompanyAPIDataContext.GetReports(companyid);
    }

}

I am not sure how to construct the routes to accept the companyid parameter, so that the report list can be fetched accordingly. Any help is sincerely appreciated.

You will need RoutePrefix for controller and Route for action method.

[RoutePrefix("api/reports")] <=== RoutePrefix
public class ReportsController : Controller
{
    [HttpGet]
    [Route("{companyid}")]  <=== Route
    public IEnumerable<PBMMMIS.Data.WebReport> Get(string companyid)
    {
        return Xerox.XCM.PBMMMIS.Data.CompanyAPIDataContext.GetReports(companyid);
    }
}

Your controller and method should look something like this:

[Route("api/reports")]
public class ReportsController : Controller
{

    [HttpGet]
    [Route("{companyid}")]
    public IEnumerable<PBMMMIS.Data.WebReport> Get(string companyid)
    {
        return Xerox.XCM.PBMMMIS.Data.CompanyAPIDataContext.GetReports(companyid);
    }
  ......
  }

and call should be :

$resource('/api/reports/:companyid', {companyid: '@@companyid'}, {
  query: { method: 'GET', isArray: true} 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM