Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Current View's Url with HtmlHelper in ASP.NET MVC 3

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?

like image 941
Saeid Avatar asked Nov 29 '22 02:11

Saeid


2 Answers

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);
 }
like image 109
Nick Bork Avatar answered Dec 10 '22 21:12

Nick Bork


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

like image 40
Nadeem Khedr Avatar answered Dec 10 '22 23:12

Nadeem Khedr