Tom
Tom

Reputation: 8681

Integration of angular 4 using angular cli and ASP.Net MVC5

I am trying to build an hybrid application using Angular 4 and MVC 5. I have generated the angular 4 structure using angular-cli. Most of the documentations that I am seeing on the internet either shows

  1. manual way to integrate or
  2. integration of mvc 5 with asp.netcore.

The manual integration shows the use of systemjs while latest angular cli doesn't generate it as it is replaced with webpack. Could somebody share an example of give me direction to do it as I am new to angular.

Upvotes: 1

Views: 1114

Answers (1)

Adnan
Adnan

Reputation: 994

You Only need to take care of Routes and some Modification in HomeController for using the Angular chtml file as default view:

1) Use "ng build" for generating dist folder(production) in angular-cli project

2) Copy your Angular dist folder into Project and rename it as what you like

3) Create a new chtml file in View -> Home folder name it ngApp.chtml

4) Copy the content of index.html file in the dist folder that you already copied in the project into ngApp.chtml it must be look like this:

@{
Layout = null;
}

<!doctype html>
<html lang="en">

<head>
<meta charset="utf-8">
<title>IchartApp</title>
<base href="/">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>

<body>
<app-root>Loading...</app-root>
<script type="text/javascript" src="~/ngApp/inline.bundle.js"></script>
<script type="text/javascript" src="~/ngApp/polyfills.bundle.js"></script>
<script type="text/javascript" src="~/ngApp/scripts.bundle.js"></script>
<script type="text/javascript" src="~/ngApp/styles.bundle.js"></script>
<script type="text/javascript" src="~/ngApp/vendor.bundle.js"></script>
<script type="text/javascript" src="~/ngApp/main.bundle.js"></script>
</body>

</html>

5) in the RoutingConfig.cs in App_Start folder you need to enable Attribute Routes:

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

        //Add this to Enable Angular Routing
        routes.MapMvcAttributeRoutes(); 

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

6) Open HomeController.cs to update default route:

 public class HomeController : Controller
{
    [Route("")] //Specify default route
    public ActionResult Index()
    {
        return View("NgApp"); //Use NgApp.chtml View instead of index.chtml of HomeContoller
    }
//Specify other Angular Routes
    [Route("company")]
    [Route("login")]
    [Route("overview")]
    public ActionResult AppBookmarkableRoutes()
    {
        return View("NgApp");
    }
}

7) Press F5 to see the angular app that integrates with Asp.net MVC

Upvotes: 1

Related Questions