Search code examples
asp.net-mvc-5angular2-routingangular2-templateangular2-servicesangular2-directives

Angularjs2 'templateUrl' in @Component - how to display razor view


How to render a ASP.NET MVC5 Razor View (.cshtml) in the 'templateUrl' in @Component. On using '/Home/Index', the page hangs.

import { Component, OnInit } from '@angular/core';
import { Product } from './model';
import { InventoryService } from './dataService';

@Component({
    selector: 'my-app',
    template: `<ul>
        <li *ngFor="let product of products">
            <h4>{{product.getProducts()}}</h4>
        </li>
    </ul>`,
    //templateUrl: '/Home/Index',
    providers: [InventoryService]
})
export class AppComponent implements OnInit {
    products: Product[];

    constructor(private productService: InventoryService) { }

    ngOnInit(): void {
        this.productService.getAll()
            .then(products => this.products = products);
    }
}

Server Side Routing (RouteConfig.cs):

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

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

Angular's main page is the MVC's shared _Layout.cshtml file:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

    <!-- 1. Load libraries -->
    <!-- Polyfill(s) for older browsers -->

    <script src="~/node_modules/core-js/client/shim.min.js"></script>
    <script src="~/node_modules/zone.js/dist/zone.js"></script>
    <script src="~/node_modules/systemjs/dist/system.src.js"></script>

    <!-- 2. Configure SystemJS -->
    <script src="~/Scripts/systemjs.config.js"></script>
    <script>
        System.import('../Scripts/main').catch(function (err)
        {
            console.error(err);
        });
    </script>
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>

The web api controller (ProductController.cs) is accessible directly and procuces valid JSON output.

[Route("api/Product/GetProducts")]
        public IEnumerable<ProductJSON> GetProducts()
        {
            IQueryable<ProductJSON> products = _context.Products.Select(
                    p => new ProductJSON
                    {
                        Name = p.Name,
                        Category = p.Category,
                        Price = p.Price
                    });
            return products.ToList();
        }

HomeController.cs is as below:-

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

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }

Index.cshtml is as below:-

@{
    ViewBag.Title = "Home Page";
}

<my-app>Loading...</my-app>

I am able to access '/Home/Index' path successfully when using 'template', but application hangs and not able to access on using 'templateUrl'

@Component({
    selector: 'my-app',
    template: `<ul>
        <li *ngFor="let product of products">
            <h4>{{product.getProducts()}}</h4>
        </li>
    </ul>`,
    //templateUrl: '/Home/Index',
    providers: [InventoryService]
}) 

Solution

  • you need a little different approach when mixing ASP.NET MVC5 and Angular, you need to separate your Root component path and ASP.NET default path.

    Try below,

    Create a new Controller let's say ComponentsController like below,

    public class ComponentsController : Controller
        {
            // GET: Components
            public ActionResult App()
            {
                return View();
            }
     }
    

    and add a Components\App.cshtml, make sure no shared _Layout is used.

         <ul>
            <li *ngFor="let product of products">
                <h4>{{product.getProducts()}}</h4>
            </li>
        </ul>
    

    update AppComponent template URL, so that it uses new path,

    templateUrl: '/Components/App' 
    

    Remove shared Layout for your Index.cshtml as well and get it served directly from Index.cshtml, fix path based on your project structure

    It should work.

    Check this Github Repo with a basic application.

    Hope this helps!!