0

I am building an app with asp.net mvc with angular 4. I have a shared layout which contain all the link of my page and it is .cshtml . When I give a link which will use angular routing.But when I click the link it is not working and page not showing.

My shared Layout link Code:

         <li><a href="@Url.Action("Index","Admin")">User List</a></li>
                        <li><a href="@Url.Action("PermissionIndex","Admin")">Permission Index</a></li>
                        <li><a href="@Url.Action("RoleCreate","Admin")">Role Create</a></li>
                        <li><a href="@Url.Action("RoleIndex","Admin")">Role Index</a></li>
                        <li><a routerLink="/homes" routerLinkActive="active">Home</a>  </li>

This is my Home Component:

    import { Component } from '@angular/core';

    @Component({
        selector: 'homes',
        templateUrl:"./home.component.html"
    })
    export class HomeComponent {

    }                   

This is App routing module:

const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  { path: 'dashboard',  component: DashboardComponent },
  { path: 'detail/:id', component: HeroDetailComponent },
  { path: 'heroes', component: HeroesComponent },
  { path: 'homes', component: HomeComponent }

];

@NgModule({
    //imports: [
    //    BrowserModule,
    //    FormsModule,
    //    RouterModule.forRoot(routes, { useHash: true })  // .../#/crisis-center/
    //],
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})

When I click on home then nothing showing up.

1 Answer 1

1

I did face the same problem while trying to add Angular to an existing ASP.Net MVC website.

I configured my routing to every path starting with "/app" to be redirected to my AppController (main page of my Application)

I had a shared Layout between the MVC and Angular pages containing the menu with a lot of @Url.Action and @Action.Links.

This was my initial MVC routing and the one that was causing the issue.

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default",
            "{controller}/{action}/{id}",
            new {controller = "Home", action = "Index", id = UrlParameter.Optional},
            new
            {
                serverRoute = new ServerRouteConstraint(url => !url.PathAndQuery.StartsWith("/app", StringComparison.InvariantCultureIgnoreCase))
            }
        );

        routes.MapRoute(
            "angular",
            "{*url}",
            new {controller = "App", action = "Index"}
        );
    }
}

The problem with this, is that an @Url.Action is being resolved:

<a href="@Url.Action("Action", "Controller")">Link</a>

on the angular page, the url.PathAndQuery will contain "/app" and will not match with the MVC route. Making impossible to resolve the @Url.Action.

For solving this I Created a custom constraint filtering by RouteDirection, matching the Default route when it is UrlGeneration (this is the value when it is trying to resolve a @Url.Action).

This is how my final routing looks like:

public class AngularConstraint : IRouteConstraint
{
    public bool Match
    (
        HttpContextBase httpContext,
        Route route,
        string parameterName,
        RouteValueDictionary values,
        RouteDirection routeDirection
    )
    {
        return routeDirection == RouteDirection.UrlGeneration ||
               !httpContext.Request.Path.StartsWith("/app", StringComparison.InvariantCultureIgnoreCase);
    }
}

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

        routes.MapRoute(
            "angular",
            "{*url}",
            new {controller = "App", action = "Index"}
        );
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.