13

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?

2 Answers 2

17

Have you tried something along these lines?

var pollAction = '<%=Url.Action("CheckStatus", "MyController") %>';
Sign up to request clarification or add additional context in comments.

1 Comment

I knew there was a simple answer out there! Thanks!
11

If your page or control inherits from 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.