Some of these answers provided here may have worked in 2014 but with newer releases of MVC, as of 2017 the routes do not work as expected or you may be be using [RoutingAttrbiutes]
which allow you to easily adjust route names and parameters.
Based on all these answers here, ShaqCode
and ByteBlocks
I built a UrlHelper extension that help us make our lives a little bit easier now.
If you include this in the global namespace you do not need to import anything and you can just use it as follows'
<a ng-href="@Url.AngularActionLink("create", "purchaseorder", "supplierId", "{{supplier.Id}}")">Create</a>
And the extension class is as follows
public static class AngularUrlHelper
{
public static List<string> RawRouteUrl;
public static string AngularActionLink(this UrlHelper html, string actionName, string controller, string routeValue, string angularBinder)
{
var actionUrl = string.Empty;
if (RawRouteUrl == null)
RawRouteUrl = new List<string>();
var routeQuery = $"{actionName}/{{{routeValue}}}";
var rawRoute = RawRouteUrl.FirstOrDefault(x => x.Contains(routeQuery));
if (string.IsNullOrWhiteSpace(rawRoute))
{
RawRouteUrl.Clear();
foreach (var r in RouteTable.Routes)
{
try
{
RawRouteUrl.Add(((Route)r).Url);
}
catch (System.Exception) { }
}
rawRoute = RawRouteUrl.FirstOrDefault(x => x.Contains(routeQuery));
}
if (!string.IsNullOrWhiteSpace(rawRoute))
{
actionUrl = rawRoute.Replace($"{{{routeValue}}}", angularBinder);
}
return actionUrl;
}
}
And the result HTML will be angular ready.
<a ng-href="/create/purchaseorder/{{supplier.Id}}">Create</a>
Some more info.
I used a static list to make a really simple caching system per Application Pool. URL's will not really change unless you publish but they can change if you edit the .chstml
file directly on the server.
So to accommodate a cache refresh, if the expected url query is not found it will attempt to rebuild the route string list.
The reason I did this cache thing is to avoid iterating constantly over the RouteTable.Routes
- I tried to find a way to easily just get the string URL values from the RouteCollection
- But for some reason it is practically impossible!? So hence.. this extension.