AngularJS - ui-router - MVC 5 - html5mode

Osm*_*MUS 6 asp.net-mvc html5 angularjs angular-ui-router

我正在尝试使用AngularJSMVC 5创建一个迷你SPA .除此之外,我想为AngularJS 使用ui-router插件而不是ng-route并且想要启用html5mode.

我的问题是,每当我点击一个锚元素时,它刷新页面并向ASP.NET MVC控制器发送请求并将所选视图放在正确的位置,我希望它不重新加载.

如果我将AngularJS路由机制更改为ng-route,那么它可以按照我的意愿工作,不刷新页面,并路由到所选视图.

在MVC 5 RouteConfig.cs文件中,

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "SpaUI",
            url: "{SpaUI}/{*catchall}",
            defaults: new { controller = "SpaUI", action = "Index", id = UrlParameter.Optional }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "SpaUI", action = "Index", id = UrlParameter.Optional }
        );
Run Code Online (Sandbox Code Playgroud)

在AngularJS的app.js文件中,

app.config(['$stateProvider', '$provide', '$locationProvider', '$urlRouterProvider', function ($stateProvider, $provide, $locationProvider, $urlRouterProvider) {

    $urlRouterProvider.otherwise('/Dashboard');

    $stateProvider
    .state("dashboard", {
        url: "/Dashboard",
        templateUrl: "AngularViews/dashboard.html"
    })

    .state("test", {
        url: "/Test",
        templateUrl: "AngularViews/test.html"
    });

    $locationProvider.html5Mode(true);
 }]);
Run Code Online (Sandbox Code Playgroud)

_Layout.cshtml文件中用于锚点;

 <a data-ui-sref="dashboard" title="Dashboard">
Run Code Online (Sandbox Code Playgroud)

在视图占位符的相同_Layout.cshtml文件中

 <div id="content" data-ui-view="" class="view-animate"></div>
Run Code Online (Sandbox Code Playgroud)

如何在不重新加载页面的情况下将所有这些内容组合在一起?任何想法都赞赏:)

Ani*_*ngh 0

或许对你有帮助!!

通过做这个:

  • 删除“app”路由的复杂性,并使用标准路由。
  • 添加重写规则。
  • 从布局中删除基本 href。

例如看起来像这样。

public static class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.LowercaseUrls = true;
        routes.MapRoute("Default", "{controller}/{action}/{id}", new
        {
            controller = "Home",
            action = "Index",
            id = UrlParameter.Optional
        }).RouteHandler = new DashRouteHandler();
    }
}
Run Code Online (Sandbox Code Playgroud)

public class DashRouteHandler : MvcRouteHandler
{
    /// <summary>
    ///     Custom route handler that removes any dashes from the route before handling it.
    /// </summary>
    /// <param name="requestContext">The context of the given (current) request.</param>
    /// <returns></returns>
    protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        var routeValues = requestContext.RouteData.Values;

        routeValues["action"] = routeValues["action"].UnDash();
        routeValues["controller"] = routeValues["controller"].UnDash();

        return base.GetHttpHandler(requestContext);
    }
}
Run Code Online (Sandbox Code Playgroud)

ETC。