在ASP.NET MVC 3中使用HtmlHelper获取当前视图的URL

Sae*_*eid 4 asp.net-mvc razor asp.net-mvc-3

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

Nic*_*ork 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
Run Code Online (Sandbox Code Playgroud)

在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);
 }
Run Code Online (Sandbox Code Playgroud)


Nad*_*edr 6

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

您可以RouteDataViewContext对象访问字典

会是这样的

@ViewContext.RouteData.Values["Controller"]
Run Code Online (Sandbox Code Playgroud)

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


Bre*_*dan 5

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