【问题标题】:Angular routing in ASP.NET MVC application, How to use ngView in Asp.Net MVC _Layout.cshtml?ASP.NET MVC 应用程序中的角度路由,如何在 Asp.Net MVC _Layout.cshtml 中使用 ngView?
【发布时间】:2016-11-23 12:14:19
【问题描述】:

我的示例应用程序有两个 MVC 控制器 1.HomeController 2.DetailsController

HomeController.cs

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }

首页 -> Index.cshtml

<div>
    Home - Index 
</div>

DetailsController.cs

public class DetailsController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }

详细信息 -> Index.cshtml

<div>
    Details - Index 
</div>

在 _Layout.cshtml 中有指向主页和详细信息的链接。

_ViewStart.cshtml

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

_Layout.cshtml

<!DOCTYPE html>
<html data-ng-app="app">
<head>
    <base href="/" />
    <title>Angular Routing</title>
    <script src="~/Scripts/angular.js"></script>
    <script src="~/Scripts/angular-route.js"></script>
    <script src="~/App/app.js"></script>
</head>
<body>
    <h1>Layout</h1>
    <a href="/Home">Home</a>
    <a href="/Details">Details</a>
    <div ng-view>        
        @RenderBody()
    </div>
</body>
</html>

当页面加载时,我从 _Layout.cshtml 获取内容,但没有任何内容加载到 ngView 容器中。

我的猜测是,angular 正在尝试加载根路由“/”的路由配置中设置的主视图。 但它通过 _Layout.cshtml 取回了完整视图,它再次尝试加载主页,并且此循环无限期地继续。

app.js

(function () {
    var app = angular.module("app", ["ngRoute"]);

    app.config(config)

    function config($routeProvider, $locationProvider) {
        $routeProvider
                      .when('/', { 
                          templateUrl: "/Home",
                      })
                      .when('/Home', {
                          templateUrl: "/Home",
                      })
                      .when('/Details', {
                          template: "/Details",
                      });

        $locationProvider.html5Mode(true);
    }               
}());

我在 Chrome 控制台中收到此错误。

angular.js:13920 RangeError: 超出最大调用堆栈大小

所以我尝试从 HomeController 返回 Partial 视图,它加载了 Home/Index 视图但 _Layout.cshtml 中的内容没有加载。

如何在MVC应用中做角路由,有没有办法使用_Layout.cshtml中的ngView?

【问题讨论】:

    标签: angularjs asp.net-mvc angular-routing asp.net-mvc-layout


    【解决方案1】:

    首先,如果你想利用 Angular 和 ASP.Net MVC,你想观看AngularJS & ASP.NET MVC Playing nice Tutorial by Miguel Castro

    您可以在GitHub 查看我的示例项目。

    这个概念是使用 MVC Route 作为 SPA 的主要入口点,然后让 Angular Route 处理各个页面的路由。主要内容是 MVC RouteConfig.cs,您希望在其中 users/{*catchall}

    仅供参考: 在我的示例项目中,我使用 MVC 的 cshtml 作为 Angular 视图。如果要使用常规 html,可以忽略。此外,我使用 Angular 1.5 组件,以便在可用于生产时轻松转换为 Angular 2。

    【讨论】:

    • 非常感谢您的回复..它真的很有帮助。
    猜你喜欢
    • 2018-04-21
    • 2016-10-22
    • 1970-01-01
    • 2017-01-12
    • 2020-01-19
    • 2018-12-14
    • 2017-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多