I found a convenient way out of this problem, thinking a little out of the box. The reason I use ActionLink really simplifies routing processing. Just put the controller and action name, and the helper generates the correct URL. To get around this in JavaScript, I first created an HtmlHelperExtender using UrlHelper to resolve the URL in the appropriate context.
namespace System.Web.Mvc.Html { public static class HtmlHelperExtensions { public static string ResolveUrl(this HtmlHelper html, string url) { var urlHelper = new UrlHelper(html.ViewContext.RequestContext); return urlHelper.Content(url); } } }
JavaScript is now easy enough to get the correct Url
$(document).ready(function () { var action = '<%= Html.ResolveUrl("~/Controller/JsonAction") %>'; // JSON controller call for model data $.getJSON(action, null, function (models) { // Do something with models action = '<%= Html.ResolveUrl("~/Controller/Details/") %>'; for (var i = 0; i < models.length; i++) { $('#modelList').append( '<tr><td><a href=\"' + action + models[i].Id + '\">' + models[i].Title + '</a></td></tr>'); } }); });
source share