Angular routing在asp.net mvc4中无法正常工作,为什么?
Angular routing在asp.net mvc4中无法正常工作,为什么?
我是Angular的新手,尝试在asp.net mvc 4应用程序中实现路由。我的控制器可以工作,路由更新但不加载视图信息。有人知道为什么吗?
JobParsing.js
var JobParsing = angular.module('JobParsing', []); JobParsing.controller('LandingPageController', LandingPageController); var configFunction = function($routeProvider) { $routeProvider. when('/routeOne', { templateUrl: 'home/one', controller: 'LandingPageController' }) .when('/routeTwo', { templateUrl: 'home/two', controller: 'LandingPageController' }); }; configFunction.$inject = ['$routeProvider']; JobParsing.config(configFunction);
LandingPageController.js
var LandingPageController = function($scope) { $scope.models = { helloAngular: '我能工作!你好!' }; }; LandingPageController.$inject = ['$scope'];
_Layout
@Scripts.Render("~/bundles/JobParsing")@RenderBody() {{models.helloAngular}}
One.cshtml(Two.cshtml相同)
路由一
Angular routing在asp.net mvc4中无法工作的原因是由于在templateUrl
中引用的文件无法被访问到。这是因为在HomeController.cs中使用了ActionResult One(),而该方法返回的是一个One.cshtml视图文件,而不是一个html文件。
要解决这个问题,需要将Controller中的方法返回一个html文件,而不是cshtml文件。可以通过修改One()方法的返回类型或者在方法中使用其他方式来返回html文件。
修改返回类型的方法如下所示:
public ActionResult One() { return Content("This is the content of One.html
", "text/html"); }
这样就可以在Angular的路由中正确引用templateUrl: 'home/two.html'
了。
Angular routing在ASP.NET MVC4中无法工作的原因是因为没有正确配置路由。
解决方法是在JobParsing.js文件中正确配置$routeProvider,并在HomeController.cs文件中添加正确的Action方法。
具体代码如下:
_Layout.cshtml
@Scripts.Render("~/bundles/JobParsing")
JobParsing.js
var JobParsing = angular.module('JobParsingApp', ['ngRoute', 'JobParsingApp.LandingPageController']); JobParsing.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) { $routeProvider. when('/routeOne', { templateUrl: '/Home/One' //controller: 'LandingPageController' <-- they are partial, you don't need }). when('/routeTwo', { templateUrl: '/Home/Two' //controller: 'LandingPageController' <-- same... adapt your routing when using complete views. }). otherwise({ redirectTo: '/' }); } ]);
LandingPageController.js
var LandingPageController = angular.module('JobParsingApp.LandingPageController', []); LandingPageController.controller('lpCtrl', ['$scope', function ($scope) { $scope.test = 'test data'; var _helloAngular = 'I work! Hello!'; $scope.models = { helloAngular: function (newMsg) { if (angular.isDefined(newMsg)) { _helloAngular = newMsg; } return _helloAngular; } }; }]);
BundleConfig.cs
... bundles.Add(new ScriptBundle("~/bundles/JobParsing").Include( "~/Scripts/JobParsing/LandingPageController.js", "~/Scripts/JobParsing/JobParsing.js" )); ...
HomeController.cs
public class HomeController : Controller { public ActionResult Index() { return View(); } public PartialViewResult One() { return PartialView(); } public PartialViewResult Two() { return PartialView(); } }
Index.cshtml
Index
One.cshtml
One
Two.cshtml
Two