如何使用cshtml实现angularjs路由

时间:2015-02-26 02:34:47

标签: asp.net-mvc angularjs asp.net-mvc-4

我正在尝试使用cshtml实现angularjs路由,但我无法完成它。有人可以看一下吗?我做错了什么。

index.cshtml:

<a href="#/route1">Route 1</a>

productmodule.js

var app = angular.module("productmodule", ["ngRoute"]);
app.config(['$routeProvider',
  function ($routeProvider) {
      $routeProvider.
                 when('/route1', {
                     templateUrl: '/Product/Details',
                     controller: 'ProductController'
                 }).
                 otherwise({
                     redirectTo: '/'
                 });
  }]);

Details.cshtml

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

<!DOCTYPE html>

    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title></title>
    </head>
    <body>
        <div ng-view=""></div>   
    </body>
    </html>

ProductController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace webapp.Controllers
{
    public class ProductController : Controller
    {
        //
        // GET: /Product/

        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Details()
        {
            return View();
        }

    }
}

我想要实现的是当我从(index.cshtml)点击Route 1链接时,我应该可以导航到Details.cshtml

1 个答案:

答案 0 :(得分:0)

当你点击你的锚标签时,它将向服务器发送请求(即MVC路由),以及“/”处的资源。由于您未指定控制器或操作,因此它将查找默认值,即Home / Index(假设您尚未更改默认路由配置)。在.NET项目中查找类似于以下内容的代码。

routes.MapRoute(
    "Default",
    "{controller}/{action}",
    new { controller = "Home", action = "Index" }
);

如果您希望产品/索引成为默认值,则可以将“Home”更改为“Product”。或者,您可以更改锚标记以指定控制器。

<a href="Product#/route1">Route 1</a>

无论哪种方式,MVC都会提供索引视图,此时Angular的路由将接管,检查“#/ route1”并加载适当的ng-view。