C# ASP.NET MVC 公共替代 UrlHelper.GenerateUrl

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/355700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 00:18:25  来源:igfitidea点击:

ASP.NET MVC public alternative to UrlHelper.GenerateUrl

c#asp.net-mvc

提问by Jennifer

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

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

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.

现在我很高兴对它进行硬编码,但如果有一种方法可以用来创建 URL,那就太好了。AjaxHelper/HtmlExtensions 包含创建超链接的方法(.ActionLink(...) 等等),但是如果你仔细研究它们的内在,它们依赖一个叫做 UrlHelper.GenerateUrl() 的方法来将控制器和动作解析为一个网址。这是内部的,所以我真的无法理解。

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

任何人都在框架中找到了一个很好的方法来做到这一点?还是我必须自己滚动?

采纳答案by mapache

Have you tried something along these lines?

您是否尝试过类似的方法?

var pollAction = '<%=Url.Action("CheckStatus", "MyController") %>';

回答by Michiel

If your page or control inherits from ViewPageor ViewUserControl, use the Url.Actionmethod.

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

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.

将它放在代码隐藏的方法中,并从 HTML 视图中调用它。