获取当前视图与的HtmlHelper地址在ASP.NET MVC 3(Get Current Vie

2019-07-28 20:55发布

我问一个类似的问题, 在这里我想这是一个非常简单的一个(当然不是对我来说)。 我有一个HTML帮助一个扩展方法,我需要获得当前视图与网址的HtmlHelper。 有没有人有任何想法?

Answer 1:

基于您的评论,你挂我想你想用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);
 }


Answer 2:

如果你想获得的路由信息​​,像被称为控制器或操作方法

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

会是这样

@ViewContext.RouteData.Values["Controller"]

RouteData字典,你可以得到大约需要的控制器,操作和额外的参数的名称中的所有信息,这取决于你想要什么



Answer 3:

如果你只是想请求的URL,那么你可以通过只得到它Request.Url对象。 这会返回一个开放的,但如果你想的原始网址,然后Request.RawUrl



Answer 4:

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



Answer 5:

您可以使用HTML辅助传递对象页作为参考,就像这样:

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

一个在视图只需使用:

@Links.GoHome(this)


文章来源: Get Current View's Url with HtmlHelper in ASP.NET MVC 3