Get Current View's Url with HtmlHelper in ASP.

2019-04-10 01:31发布

I ask a similar question here I think this is a really easy one (of course not for me). I have a extension method for Html helper and I need to get current view's url with HtmlHelper. Does anyone have any idea about it?

5条回答
太酷不给撩
2楼-- · 2019-04-10 01:57

If you just want the requested url then you can just get it via the Request.Url object. This returns a Uri, but if you want the raw url then Request.RawUrl.

查看更多
beautiful°
3楼-- · 2019-04-10 02:12

You could use the Request.RawUrl property or Request.Url.ToString() or Request.Url.AbsoluteUri.

查看更多
可以哭但决不认输i
4楼-- · 2019-04-10 02:17

You can use a Html Helper passing the object page as reference, like this:

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

An in the View just use:

@Links.GoHome(this)
查看更多
Ridiculous、
5楼-- · 2019-04-10 02:23

Based on your comment and the original thread you linked to I think you want to use a Url helper to get the URL for the form action, but I could have misunderstood what you wanted:

In a View:

 @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

In a HTML Helper:

 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);
 }
查看更多
贪生不怕死
6楼-- · 2019-04-10 02:23

if you want to get information about the route information , like the controller or action method that are called

you can access the RouteData dictionary from the ViewContext Object

will be like this

@ViewContext.RouteData.Values["Controller"]

with the RouteData Dictionary you can get all the info needed about the controller , action and extra parameters' name , depending on what you want

查看更多
登录 后发表回答