ASP.NET MVC公共替代UrlHelper.GenerateUrl

Jen*_*fer 13 c# asp.net-mvc

我想在我的页面中嵌入一个控制器动作的链接,以便我可以从javascript使用它.就像是

var pollAction = '/Mycontroller/CheckStatus'
Run Code Online (Sandbox Code Playgroud)

现在我很乐意对它进行硬编码,但如果有一种方法可以用来创建URL,那将会非常好.AjaxHelper/HtmlExtensions包含创建超链接的方法(.ActionLink(...)等),但是如果你研究它们的内容,它们依赖于一个名为UrlHelper.GenerateUrl()的方法来解析控制器和动作.一个网址.这是内部的,所以我无法真正理解这一点.

有人在框架中找到了一个很好的方法吗?或者我必须自己动手?

map*_*che 17

你有没有试过这些方面的东西?

var pollAction = '<%=Url.Action("CheckStatus", "MyController") %>';
Run Code Online (Sandbox Code Playgroud)


Mic*_*iel 11

如果您的页面或控件继承自ViewPageViewUserControl,请使用该Url.Action方法.

如果没有,请改用:

 String url = RouteTable.Routes.GetVirtualPath
              (
                ((MvcHandler) HttpContext.Current.CurrentHandler).RequestContext,
                new RouteValueDictionary
                (
                  new 
                  { 
                    controller = "MyController", 
                    action = "CheckState", 
                    id = idParameter 
                  }
                )
              ).VirtualPath;
Run Code Online (Sandbox Code Playgroud)

将它放在代码隐藏的方法中,然后从HTML视图中调用它.