4

我在这里问了一个类似的问题,我认为这是一个非常简单的问题(当然不适合我)。我有一个 Html 助手的扩展方法,我需要使用 HtmlHelper 获取当前视图的 url。有人对此有任何想法吗?

4

6 回答 6

9

根据您的评论和您链接到的原始线程,我认为您想使用 Url 助手来获取表单操作的 URL,但我可能误解了您想要的内容:

在视图中:

 @Url.Action(null) returns the current controller/action
 @Url.Action("Action") returns a custom action with current controller
 @Url.Action("Action","Controller") returns a custom controller and action

在 HTML 助手中:

 public static MvcHtmlString MySpecialHelper(this HtmlHelper htmlHelper)
 {
      UrlHelper urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext,htmlHelper.RouteCollection);
      string url = urlHelper.Action("Controller","Action");

      //To get the action based on the current Action/Controller use:
      url = urlHelper.Action(htmlHelper.ViewData["action"] as string);

      //or
      url = urlHelper.Action(null);

      return new MvcHtmlString(url);
 }
于 2012-04-09T14:14:12.597 回答
6

如果您想获取有关路由信息的信息,例如调用的控制器或操作方法

您可以从对象访问RouteData字典ViewContext

会是这样

@ViewContext.RouteData.Values["Controller"]

使用RouteData字典,您可以获得有关控制器、操作和额外参数名称所需的所有信息,具体取决于您想要什么

于 2012-04-09T13:56:15.883 回答
5

如果您只想要请求的 url,那么您可以通过Request.Url对象获取它。这会返回一个 Uri,但如果你想要原始 url,那么Request.RawUrl.

于 2012-04-09T13:36:44.827 回答
2

死灵术

public static MvcHtmlString MyHelper(this HtmlHelper htmlHelper)
{
    var url = htmlHelper.ViewContext.HttpContext.Request.Url;
    //more code
}

OP 询问“Html 助手的扩展方法” - 所以是的,就是这样。

于 2019-11-08T20:48:12.060 回答
0

您可以使用 Html Helper 传递对象页面作为参考,如下所示:

@helper GoHome(WebViewPage page)
{
   <a href="@page.Url.Action("Index", "Home")"></a>
}

在视图中只使用:

@Links.GoHome(this)
于 2014-01-31T18:48:13.810 回答
0

您可以使用 Request.RawUrl 属性或 Request.Url.ToString() 或 Request.Url.AbsoluteUri。

于 2012-09-21T10:27:37.200 回答