AngularJS - ui-router - MVC 5 - html5mode

I am trying to create a mini SPA with AngularJS and MVC 5 . In addition to this, I want to use the ui-router plugin for AngularJS instead of ng-route and I want to enable html5mode .

My problem is that whenever I click on the anchor element, it refreshes the page and sends a request to the ASP.NET MVC controller and puts the selected view in the right place, I want it to not reload.

If I change the AngularJS routing mechanism to ng-route, then it works the way I wanted, does not refresh the page and does not direct the selected view.

In the MVC 5 RouteConfig.cs file,

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 } ); 

In the app.js file for AngularJS,

 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); }]); 

In the _Layout.cshtml file for anchors;

  <a data-ui-sref="dashboard" title="Dashboard"> 

In the same _Layout.cshtml file for the replacement view

  <div id="content" data-ui-view="" class="view-animate"></div> 

How can I combine all these things without reloading the page? Any ideas are welcome :)

+6
source share
1 answer

It can help you!

By doing this:

  • Remove the complexity of the application route and use the standard route.
  • Add a rewrite rule.
  • Remove the base href from the layout.

For example, look like this.

 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(); } } 

and

 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); } } 

and etc.

0
source

Source: https://habr.com/ru/post/977243/


All Articles