Few ways to pass values to a Function in Isolate scope : {{AngularJS}} – Part 12

Custom Directives in AngularJS is pretty vast topic. I thought of covering it in a single post but as I started writing, count is just increasing as I don’t want to leave any important and relevant aspect. This is third post on custom directive and twelfth post in the series of AngularJS (Click here to see all the post). Till Now, we have discussed that how to create a basic custom directive in first post then in second , we discussed about creating custom directive with isolate scope. The link of those two posts are below –

  1.  Creating custom directive in AngularJS – Part 9
  2.  Create Custom Directive using Isolate scope in AngularJS – Part 10

In my last post, I discussed about various options available while creating isolate scope in custom directives and  three different types of Local Scope properties. These are

1) @ or @attr

2) = or =attr

3) & or &attr

In this post, I am going to discuss more about the third option. It allows us to wire up some external expression to the custom directive as discussed in the last post. Let’s see the pic from last post about the third option in isolate scope

expressionAs the primary benefit of the custom directive is re-usability and to get the most benefit out of it , we need to use isolate scopes. Apart from that, it is common where we need to pass some values to the external function. Although Angular does not provide any direct way to achieve it but there some other workarounds. Let’s start exploring

Here we are passing UpdateData expression in the isolate directive. Now let’s see what should we do if we want to pass some values in this method. There could be multiple ways, I am going to discuss a few.

First Option:  In this scenario, let’s say we have some data that is available in the custom directive itself that we need to send to in external expression as parameter. For this, I added an input text box in template that I will be using the entered value as parameter for the external function. Let’s first see the directive

<expcustomdirective expr="UpdateData(updatedName)" talkname="{{talk.name}}" />

Here I am passing a parameter named updatedName in UpdateData. So let’s change the method accordingly

$scope.UpdateData = function (modifiedName) {
    $scope.talk = {
        name: modifiedName,
        duration: '45m'
    };
};

Now let’s see the custom directive

myangularapp.directive('expcustomdirective', function () {
    var directive = {
        restrict: 'E', // restrict this directive to elements
        scope: { method: '&expr', talkname: '@' },
        template: "<input type='text' ng-model='mytalkName'/><div>{{talkname}}</div> <input type='button' " +
            "ng-click='method({updatedName : mytalkName})' value='Update Data'/> "
    }

    return directive;
});

In the template above, I added an input text box and provided the model (ng-model) name as myTalkName .Another important point (ng-click) to see here, how the value is passed. Here we need to provide an object map so that it gets bound correctly as {updatedName : mytalkName}. Now, Lets see it running

firstoptionWe can see here that we can easily get a value that is part of custom directive itself and use it in external expression.

Second Option – We discussed in first option that how can we pass some value which is generated from the directive itself. Lets take another scenario, where you need to pass the values that is available outside.

We know that the compilation process involves two steps in Angular – One is compiling and another is linking. Linking has the responsibility to assign the scope to directive. We can take the help of linking function to pass some values in the external function. While writing to custom directive, we can attach  a function to link as

link: function (scope, element, attrs) {

}

This gets called once for the custom directive. Here it has three parameters.

scope – It is the isolated scope that is available for the directive.

element – It is a custom directive element.

attrs– List of attributes available in custom directive.

So lets update our custom directive .

var myangularapp = angular.module("myangularapp", []);
myangularapp.directive('expcustomdirective', function () {
    var directive = {
        restrict: 'E', // restrict this directive to elements
        scope: { method: '&expr', talkname: '@' },
        template: "<div>{{talkname}}</div> <input type='button' " +
            "ng-click='method(updatedName)' value='Update Data'/> ",
        link: function (scope, element, attrs) {
            scope.method({ updatedName: "Updated topic name" });
        }
    }
    return directive;
});

See the link part in above code , It is calling the external expression that got assigned to method property of isolate scope  and passing the parameter as you can see above. Here also the parameter is passed using object map. But here if we run the the page, then this method will be called by default called as link will be executed while load.

Third approach – This is similar approach with above but we will further enhance it. As I discussed above that attrs contains all the attributes of the custom directive. So we can set some value in attribute that we can read later. Let’s see with an example

<expcustomdirective expr="UpdateData(updatedName)" talkname="{{talk.name}}" talknewname ="Update Talk name via attribute"/>

So here I added an attribute as TalkNewName that we will use and pass it in the expression. Let’s see How?

myangularapp.directive('expcustomdirective', function () {
    var directive = {
        restrict: 'E', // restrict this directive to elements
        scope: { method: '&expr', talkname: '@' },
        template: "<div>{{talkname}}</div> <input type='button' " +
            "ng-click='method({updatedName : NewTalkName})' value='Update Data'/> ",
        link: function (scope, element, attrs) {
            scope.NewTalkName =  attrs.talknewname;
        }
    }
    return directive;
});

In above code, if we see the link function then here, we are creating a new property (named NewTalkName) in isolated scope and assign value from the attribute (See inside link). Now again, if we see ng-click in the code, I am mapping the argument name with new property added in the scope. Let’s run it.

ThirdOptionNote – AngularJS converts camel-case to snake-case when moving from JavaScript to HTML or vice-versa. Like if you added an attribute with name talkNewName, it will be accessed id JavaScript by talknewname only. I spent lots time to figure it out.

So in this post, different work around of passing values in the external expression. It can be helpful in many different scenarios. You yourself can explore some other options if it does not serve your need but there is no direct way in AngularJS . Above code may also not look very intuitive but it solves the purpose. Complete example is attached.

Hope you have enjoyed the post.

Cheers
Brij

Your Dependency Injection ready ASP.NET : ASP.NET 5


Dependency Injection has become one the key design patterns of the current projects. It helps in writing loosely coupled code which makes the code easily testable and maintainable. As per wiki

Dependency injection is a software design pattern that implements inversion of control for software libraries. Caller delegates to an external framework the control flow of discovering and importing a service or software module specified or “injected” by the caller.

In this post, we will see that how easily we can implement this pattern with ASP.NET 5 projects and leverage various available options .

ASP.NET 5 got completely redesigned and made DI friendly. It provides a by default container which can be used while writing the application. It also enables us to use third party containers with it and you may need a adapter to use with ASP.NET.

In ASP.NET 5, there is a new file added with the name startup.cs, which is the entry point of your ASP.NET application. It has two methods

1- public void ConfigureServices(IServiceCollection services)

2- public void Configure(IApplicationBuilder app)

ConfigureServices is a global method where all the services should be registered. Then all these services are available through out the application. Let’s first see that what all methods are available

DIOptionsNow let’s discuss one by one.

AddTransient – Registering a service via this method will create a new service instance each time accessed. Let’s see it via an example.

In this example, I have created a simple MVC application from an ASP.NET 5 Empty Project. Added on HomeController and Index view. I created a Repository as follows

    public interface IRepository
    {
        int GetnUpdateCounter();
    }
    public class MyRepository : IRepository
    {
        private int i;
        public int GetnUpdateCounter()
        {
            return i++;
        }
    }

In the above repository, I have a private integer variable which I am updating and returning via the method. This repository I will be using two or more places to show you the behavior. I have used it in my HomeController as

    public class HomeController : Controller
    {
        [Activate]
        public IRepository myRepository { get; set; }
        // GET: /<controller>/
        public IActionResult Index()
        {
            ViewBag.Counter = myRepository.GetnUpdateCounter();
            return View();
        }
    }

I also created a custom tag helper (To learn about Tag helper in detail – Click here) as

    public class TestTagHelper : TagHelper
    {
        [Activate]
        public IRepository MyTalkRepository { get; set; }
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            output.TagName = "h5";
            output.Content = "From TagHelper - " + MyTalkRepository.GetnUpdateCounter().ToString();
        }
    }

In the tag helper above, I am using the Repository again and displaying it in an element. This tag helper is used in the Index View. My Index view looks like

@addtaghelper "DI"

<div style="font-family:Verdana; font-size:small">	
	<h2>Dependency Injection demo</h2>
    <h3>@ViewBag.Counter</h3>
    <test></test>
</div>

Now in the above view, I am showing the counter which I got it from Repository which is injected in HomeController.

The Repository is added in StartUp file as

public void ConfigureServices(IServiceCollection services)
{
    <strong> services.AddTransient<IRepository, MyRepository>();</strong>
     services.AddMvc();
}

Here I used AddTransient to register the Repository. Now let us run this code

TransientWe can see here that we see 0 at both places. It means there are two instances get created for the repository as expected.

AddScoped – Registering a service via this method can be really useful if we want to use the same instance while processing a particular request. Say we are using the service at two places as above – one in Taghelper and other in controller. The same instance will be available. Let’s see it via an example

All the above code would be same, the only change would be the way we register in ConfigureServices method as

public void ConfigureServices(IServiceCollection services)
{
    <strong>services.AddScoped<IRepository, MyRepository>();</strong>
    services.AddMvc();
}

Here I used AddScoped. Lets run the code again

ScopedFrom the above screen, we can say that in a request, same instance of repository is used because here the counter is maintaining the state.

AddSingleton – As the name suggests, here on first request the instance of Repostory is created and the same will be used in across all requests. Let’s change the code for registering it as

Singleton

Here we can see that state is maintained across multiple request.

AddInstance – This is similar to AddSingleton but the only difference is here that here the responsibility to create the instance is upto the developer.So lets create the instance and add that in Startup.cs as

private IRepository myRepositoy;
public Startup()
{
	myRepositoy = new MyRepository();
	myRepositoy.GetnUpdateCounter();
}
  
public void ConfigureServices(IServiceCollection services)
{
    services.AddInstance(myRepositoy);
    services.AddMvc();
}

Here I created the instance in constructor and added the instance.I purpose fully called the method in constructor to change the state of repository instance. Now lets run the code

Instance

Here we can see that the same instance (with same state) is used in across requests.

One of the classic example of this scenario would be a to create Configuration object.

Note – For the sample, Visual Studio 2015 CTP6 is used. In final release the feature may get changed slightly.

In this post, we discussed the default DI container available with ASP.NET 5. Demo is attached with this post. I created different folder named startupfiles which contains the startup.cs for all four scenarios. Use those files as we discussed to run each scenario.

Hope you have enjoyed the post.

Cheers,
Brij

Recap – Presented on ASP.NET 5 at #GIDS Banglore – Download Slides and demo

IMG_9518 - Copy

Great Indian Developer Summit (GIDS) is Asia’s largest technology event where thousand of developers joins each year. The event took place at IISc Bangalore during 21-24 April 2014 where many veteran speakers presented on various topics.

This year, I gave an one hour Talk on one of my favorite topics – ASP.NET 5. ASP.NET is always very near and dear to me and it got more awesome because of the kind of changes is taking place in coming version. People were very enthusiastic about the talk and the Hall got full ten minutes before the schedule and some of them were event standing at the back. Although it was a completely demo oriented session where I wrote the code live on Visual Studio 2015 but I presented few slides to give the audience bigger picture.

I talked on the core changes of ASP.NET 5 and discussed Middle-ware, Dependency Injection, Configuration management etc. Please find my slides below.

The sample project that we created during the talk, can be downloaded from below link.

Note – Visual Studio 2015 CTP6 is used for this Demo.

To know more about GIDS click here.

Hope you all have enjoyed the talk and let me know you want to hear something specific.

Cheers
Brij

Presenting on ASP.NET 5 in #GIDS2015

GIDS_Website_LogoThe Great Indian Developer Summit (GIDS) is the largest and most popular annual conferences of India. This year it is taking place during April 21-24, 2015. I am very excited to share that I will be presenting there on ASPNET5 which was always very near to me . This version is bit different from earlier releases due to the massive changes that are taking place with it in this version. All the slides and the demos will be shared at the end of session. The details of of Talk are as below

BrijB1

Building Modern Web Applications with ASP.NET 5

ASP.NET 5 is now redesigned to cater to the needs of modern web applications. With the redesign, you can now  use the latest best practices such as dependency injection, TDD etc. ASP.NET 5 curtails many modules and components that we normally don’t use in our projects and hence boosts application speed. In this session we will examine the design shift that took place within ASP.NET 5 and how it resolves several of the problems that we encounter in our coding lives. At the end of session, you will have a good idea on the changes that ASP.NET5 brings to you as a developer.

If you are visiting this time, I will highly recommend to join this session for an hour and explore the awesomeness of ASP.NET 5. This session will be driven by demos with lots of Interactions

I am very excited to see you all there.

Cheers,
Brij

What is View component: ASP.NET 5

This is the second post on ASP.NET 5. In this post, we are going to explore one another very useful feature of ASP.NET 5. The link of my earlier post on ASP.NET 5 is

 Getting started with Tag Helpers – ASP.NET 5

ASP.NET 5 comes with another version of ASP.NET MVC that is ASP.NET MVC6.View Component is another very powerful got added with MVC 6. If you have not already gone through with this feature, you might just keep guessing about it and may correlate with multiple things. But this feature when you go through, you will enjoy it.

Before discussing this, How many of used Child Actions or know about that?

If you have used that you must have find it bit nasty. Child Actions are like a normal action but it can not be called by directly from url instead it is called from a view. The key usage of Child Action, when we want to reuse some part of UI at multiple places then we create a child action and use it at multiple places. One of the key issues was that with this, it makes another request to the server to call the action method, by going through the whole life cycle which makes the application slow. Also It can not be invoked asynchronously.

View Component provides us capability to write a component that generates a part of the UI similar to Partial View . It can be reused on  different places based on the requirement. One of the classic example could be a shopping cart that is visible to user on every page and many similar others. Now you no longer need Child Action after using it.

So How to create a ViewComponent ?

There are two part of that

1- Create a class that derives from class ViewComponent

2- A razor view which will be using the ViewComponent class by calling its method.

You can think of the class as a mini-controller and another one as a view. Let’s create an example,

Say I want to show Top Users of the website and showing them on each page in a section. So let’s create a View Component Class

 public class TopUsersViewComponent : ViewComponent
	{
		public IViewComponentResult Invoke(int TopUserCount)
		{
			var items = GetUsers().OrderByDescending(u => u.Points).Take(TopUserCount);

			return View(items);
		}

		public IList<UserInfo> GetUsers()
		{
			IList<UserInfo> users = new List<UserInfo>()
				{
				new UserInfo() { UserName = "Amit", Points= 1000 },
				new UserInfo() { UserName = "Brij", Points= 1500 },
				new UserInfo() { UserName = "Rahul", Points= 500 },
				new UserInfo() { UserName = "Vivek", Points= 400 },
				new UserInfo() { UserName = "Gaurav", Points= 600 },
				new UserInfo() { UserName = "Abhijit", Points= 1200 },
				new UserInfo() { UserName = "Peter", Points= 1100 },
				new UserInfo() { UserName = "Satya", Points= 300 }
				};

			return users;
		}
	}

Few points –

1- Note here that the class name ends with ViewComponent and the name would be TopUsers only similar to controllers. If you don’t want to add this suffix then you can provide an attribute on the class as [ViewComponent(Name = “TopUsers”)] then you can give whatever name you want.

2- Here Invoke would be fired and for each View Component instance. We can pass as many parameters as we require. There is async version of this method is also available which can be very useful if you are connecting to some third party component or you know this would be long process.

We have already created the class. Now lets create the View. Here we need to follow certain structure to create the View. For this example, I have created a MVC controller named as DemoController and created an Index view. As We are going to use the View Component here, we need to create the folder structure like Views\<ControllerName>\Components\<ViewComponentName>\. For this example it is as Views\Demo\Components\TopUsers\. So we need to create a view in this folder as Default.cshtml. It is as

@model IEnumerable<WebApplication1.Models.UserInfo>

<h3>Top Users</h3>
<ul>
@foreach (var user in Model)
{
<li> <img src= @user.ProfilePic /> @user.UserName</li>
}
</ul>

So we have created a View Component named as TopUsers. Now lets use this in View. It would be as

<div class="col-md-4">
@Component.Invoke("TopUsers", 3)
</div>

It’s simple. We need to pass the name of the View Component and other parameters of Invoke method. Now it’s time to run the code. So it’s look like
DemoEx

The encircled content is rendered via View Componet. Now we can use this as many places as we require. So now there is no need of Chiild Action and Partial Views.

Hope you have enjoyed the post and this new feature. I will posting some more post on the new feature and changes in ASP.NET5.

Happy Learning,
Brij

Getting started with Tag Helpers – ASP.NET 5

ASP.NET has been always near and dear to me and it got more exciting for me as ASP.NET5 got revolutionary changes comparing to previous versions. All the changes has been done considering key points that are driving the software evolution like Agility, embracing latest design standards and technologies. It provides more capabilities, more power to developer, follows latest standards and helps in writing Cloud and mobile ready applications. As we know ASP.NET is like a umbrella of technologies and consists of ASP.NET MVC, ASP.NET WebForms, ASP.NET web api etc. All these technologies got lots of change and design to serves the modern web apps. ASP.NET5 comes with another new version of ASP.NET MVC6. I will be writing couple of posts on cool features of ASP.NET 5 that actually makes our life easy as a developer.

In this post, I am going to discuss one of the main features of ASP.NET 5 that I really liked a lot. When razor syntax was introduced, it looked different and sometimes uncomfortable to me. There were multiple reasons. First thing, I loved the idea of writing C# code at in different file as code behind because it gave clear separation of markup and c# code. It also provided to leverage the real IDE power like intellisense for html, css, JavaScript, other plugins and was easily integrable with other plugins. Razor removed the concept of code behind and allows us to write to inline C# code. Although it is powerful at certain times but it is confusing sometimes as well and make a markup writing experience very bad. Because here we were not writing the HTML actually we were writing a mix and match of html and some C# methods that renders the html while executing at run time. So we used to get the issues while running the code only.

We have used a inbuilt HTML helpers in razor forms a lot and created custom helpers when required. Our normal Razor view looks like

// LOOSELY TYPED VIEW
<div class="editor-label">
// For Label
@Html.Label("Name", new {id= "lblName"}
</div>
<div class="editor-field">
// For textbox
@Html.Editor("txtName")
</div>
// For action link
<li>@Html.ActionLink("Home", "Index", "Home")</li>
// STRONGLY TYPED VIEW
@Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
    @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
    @Html.ValidationMessageFor(m => m.UserName, "", new { @class = "text-danger" })
</div>

In above example, top three html helpers : for label, textbox and link are loosely typed view and last sectionis part of a  strongly typed view .  As earlier mentioned, we can see that it is combination of HTML and inline C# which we start with @. While rendering these html helpers methods gets called which returns the html that is rendered in browser.

ASP.NET 5 introduced new features named as TagHelpers. This is going to make developers life very easy and make the form, readable, maintainable and manageable.

First thing how to use

As we all know that in ASP.NET 5, the features were developed as independent components and can be added on demand via nuget. So we need to add it via nuget.

  1. Add Microsoft.AspNet.Mvc.TagHelpers

2 Then add it in View where you want to use this feature as @addtaghelper “Microsoft.AspNet.Mvc.TagHelpers”

Now I can use the awesomeness of tag helpers in our view. We can remove the below line

@Html.LabelFor(m => m.UserName, new { @class = “col-md-2 control-label” })

and instead can use

<label for=”UserName” class=”col-md-2 control-label” style=”color:red”></label>

It will work same as HTML helper. Under the hood the tag helper convert it to similar earlier lambda expression to get the property name.

Similarly for input

@Html.TextBoxFor(m => m.UserName, new { @class = “form-control” })

can be replaced with

<input form=”UserName” class=”form-control” style=”color:red” />

I have taken register page of starter web application which is as

razor-registerLooks as below after replacing normal razor syntax with tag helpers

taghelper-registerThis is awesome right. Now it looks cleaner, manageable and the best thing is you’ll get all the intellisense feature for HTML, css, javascript etc.

It’s not just yet. It also gives us power of creating our own tag helpers which we can create based on our need and render the appropriate html at runtime.

How to create Custom Tag Helper :

Creating custom tag helper is very easy. One need to create a class that inherits TagHelper class. So here we need to override one of these methods

1-  public override void Process(TagHelperContext context, TagHelperOutput output)

2-  public override void ProcessAsync(TagHelperContext context, TagHelperOutput output)

ProcessAsync is the asynchronous method that we can use if we need to do some long operations like getting data from database, calling any third party services etc. It has two parameters of .type TagHelperContext and TagHelperOutput. TagHelperContext  context contains the execution context for Taghelper and TagHelperOutput that contains the information that is required to generate the html. Here we provide all the details of html tags that will be generated while rendering

So for an example, I am going to create a simple status tag helper which displays different color based on some data. So my custom tag helper looks like

[ContentBehavior(ContentBehavior.Replace)]
    public class StatusTagHelper : TagHelper
    {
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            int status;
            output.TagName = "img";
            Int32.TryParse(context.AllAttributes["val"].ToString(), out status);
            if (status == 0)
            {
                output.Attributes["src"] = "images/green.png";
            }
            else if (status == 1)
            {
                output.Attributes["src"] = "images/red.png";
            }
            else
            {
                output.Attributes["src"] = "images/blue.png";
            }
        }
    }

This custom tag is used as

<div class="form-group">
    <label class="col-md-2 control-label"> Status</label>
    <div class="col-md-10">
        <status val="1"></status>
    </div>
</div>

Now if we see the C# code then you can find that attribute val is read from the context object and the details of the HTML tags are provided with the output object. One other item, you must be seeing the ContentBehavior attribute, what is the need? It plays a vital role in the tag helper. It tells that the way tag helper would render. Like here, I have used Replace, which means the tag used in cshtml will be replaced. There are four other options – None, Prepend, Append, Modify. It behaves as the name suggests, I will leave this for you guys to explore.

Let’s see the code running

customtaghelperHere the val is assigned to 1 and based on that image is rendered.

This is a simple example that I showed here to explain the Tag Helper. Creating taghelper is very simple and very flexible. Hope you have enjoyed the post. Wait for more articles on ASP.NET 5.

Happy Learning,
Brij

ASP.NET MVC and Angular Routing together – Part 11

[To view earlier posts of the series – Click Here]
This will be short but very helpful post. I have seen lots of questions and confusion over Angular Routing and ASP.NET MVC Routing. In this post, I will try to unravel. We all already know the following two points

1- ASP.NET MVC is a server side technology so it means ASP.NET MVC routing takes place at Server.

2- AngularJS is a client side technology so Angular routing itself cannot conflict with ASP.NET MVC in any way. But it works on the top of the ASP.NET MVC. Let’s discuss it with a example.

I will be taking the sample from one of my earlier posts (Learning {{AngularJS}} with ASP.NET MVC – Part 5) on AngularJS and modify a bit for this post. Let me brief about the\example

1- It has one MVC controller – named EventsController that has three methods. One returns the index view and in rest of the two, one returns a list of talks and other, list of speakers in JSON format.

2- It has two angular routes, one for listing speakers (/Events/Speakers) and another from listing talks (/Events/Talks). These urls are used in top menu. So when we run the application and the url (http://localhost:<port>/ or http://localhost:<port>/events or http://localhost:<port>/events/index) the page loads as homeAfter clicking the the two tabs talks or speakers are loaded accordingly. Angular Routes in the sample are defined as

var eventModule = angular.module("eventModule", []).config(function ($routeProvider, $locationProvider) {
 //Path - it should be same as href link
 $routeProvider.when('/Events/Talks', { templateUrl: '/Templates/Talk.html', controller: 'eventController' });
 $routeProvider.when('/Events/Speakers', { templateUrl: '/Templates/Speaker.html', controller: 'speakerController' });
 $locationProvider.html5Mode(true);
 });

Now if we access the direct angular defined routes (like ) it does not work. Let’s understand why?

When we access the url http://localhost:48551/events/index then it actually calls the MVC EventsController and Index action as expected and loads the page. Now when we click on one of the tabs (say speaker) then Angular chips in and it loads the angular view. The call does not go to MVC controller and action at server rather it gets handled at client side by Angular. It loads the data via angular service that initiates the ajax call to server to get the data. Here the url changes but handled at client side only and server (or say ASP.NET MVC) does not even get to know about it.

Now the next question, in second case, why the call does not go at server? In first case, there is nothing available at client side and request goes to the server and gets the page. When page loads it loads everything including angular library. Now when second time, the url gets changed Angular checks whether it can handle the url if yes then it just process it at client side and if not then try to load otherwise url if defined else loads nothing and leave it empty. The whole process can be defined it pictorially

ngrouteupdatedNow we can imagine a scenario while accessing a Angular defined url (http://localhost:48551/Events/Talks) as initial request, it finds nothing at client side which can handle it as it is a fresh request. And it goes to server and tries to find the EventsController and Talks action but it is not defined by ASP.NET MVC so it does not work. We just have Index action at MVC controller. Now how to resolve this issue?

As Initially in this post, I pointed out that Angular defined urls are handled at Client side only, so AngularJS must be loaded and initialized before it can handle the request. There would be two steps involved

1- All angular defined urls should be mapped to a MVC route that returns the response to client with all the client side libraries including Angular.

2- Then as angular is initialized, it handles the url as discussed earlier When we try to access an angular defined urls as first request, it goes to server then we need to initialize the page first with AngularJS then rest angular takes care.It means that in the example, we need to call the index action when somebody try to access the AngularJS urls (Talks and Speakers) directly which will load the page and it will initialize the Angular as well then the Angular urls will be handled by angular itself. So how to do that, we just need to add some routes in Global.asax of so that even if Angular defined urls are called it returns fires of the index action only. So we can add it like

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

 routes.MapRoute(
 name: "EventsCourses",
 url: "Events/Talks",
 defaults: new { controller = "Events", action = "Index", id = UrlParameter.Optional }
 );
 routes.MapRoute(
 name: "EventsSpeakers",
 url: "Events/Speakers",
 defaults: new { controller = "Events", action = "Index", id = UrlParameter.Optional }
 );

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

So here I added two routes EventsCourses and EventsSpeakers for Angular Urls and for both, index action of events controller gets called.

Here we should not have a URL which can be processed by Angular and MVC both in that case you will get different behavior in both the case so we should keep in mind while defining the URLs. So I hope it must have been clear to you. Also you do not need to add each AngularURL as new route in Global.asax, you can have unique pattern in Angular URLs and for that pattern, you can have just one route which return the same action for that pattern. Sample is attached with the post.

[Update : Updated the flow diagram of this post and content to add some clarification in a scenario when requested url is not defined in URL – 04th May 15]

Happy Learning
Brij