tags:

views:

2182

answers:

2

I want to embed a link to a controller action in my page so I can use it from javascript. Something like

var pollAction = '/Mycontroller/CheckStatus'

Now I am happy to hardcode it, but it would be really nice if there were a method I could use to create the URL. The AjaxHelper/HtmlExtensions contain methods to create hyperlinks (.ActionLink(...) and so on), but if you look into the guts of them, they rely on a method called UrlHelper.GenerateUrl() to resolve a controller and action into a url. This is internal so I can't really get at this.

Anyone found a good method in the framework to do this? Or must I roll my own?

+5  A: 

Have yo tried something like this?

var pollAction = '<%=Url.Action("CheckStatus", "MyController") %>'
mapache
I knew there was a simple answer out there! Thanks!
Jennifer
+4  A: 

If your page or control inherits from the ViewPage or ViewUserControl, use the Url.Action method.

If not, use this instead:

 string url = RouteTable.Routes.GetVirtualPath(((MvcHandler)HttpContext.Current.CurrentHandler).RequestContext,
 new RouteValueDictionary(new { controller = "MyController", action = "CheckState", id = idParameter })).VirtualPath;

Place this inside a method on your code behind and call it from the Html view.

Michiel