How to use AngularJS directive in MVC ActionLink

If you are using AngularJS in combination with ASP.Net MVC, sooner or later you will run into situation where you want to use Html.ActionLink or Url.Link to generate links on the pages. This is all well and good unless you want to create links that require some values to be included or updates from your AngularJS scope or model. Consider the following case.

@Html.ActionLink("User Details", "Details", "User", new{id="{{}}}", null)

Very quickly you will realize that it is not working as you were expecting. This line of code has generated link that looks like below.

<a href="/User/Details/">User Details</a>

Angular directive has been url encoded. So when page renders you have an invalid link. There is no direct way out of it. MVC framework implementation url encodes the URL that is generated by Html.ActionLink and Url.Link.

Decode to fix it

You can fix this issue by using following approach.

var url = Url.Action("Details", "User", new{id="{{}}"});
url = HttpUtility.UrlDecode(url);
<a data-ng-href="@url">Home</a>

  • First the link URL has been generated by using standard HtmlHelper or UrlHelper method.
  • Then URL is decoded to remove the encoding
  • Third when you generate the link, make sure you are using ng-href directive

That's all that you will need to get Html.ActionLink or Url.Link to work in your razor page used in your AngularJS application.




25.2 °C / 77.3 °F

weather conditions Haze

Monthly Posts

Blog Tags