M Kenyon II
M Kenyon II

Reputation: 4264

Alternative to using Request.URL and Request.URLReferrer to get the current link in MVC?

I was hoping to write a method/property in my BaseController class that would enable any action to get the current URL. If I call localhost/Keyword/Edit/1 I can use Request.Url to get the url. However, if there is a partial view in my Edit view, I need to use Request.UrlReferrer to get localhost/Keyword/Edit/1. If I use Request.Url while in the action for the partial view, I would end up with localhost/Keyword/PartialView.

Is there a built in way to always get the Url that would be in the browser address bar regardless of whether I'm in a View or Partial View?

Upvotes: 0

Views: 1584

Answers (1)

rohitreddyk
rohitreddyk

Reputation: 337

Create a custom HtmlHelper.Your HtmlHelper's ViewContext property will have just about everything you need about the particular request: HttpContext, RequestContext, RouteData, TempData, ViewData, etc.

To get the current path of the request, try helper.ViewContext.HttpContext.Request.Path

You can check the RouteData and obtain the (partial) action and controller, among other route values:

public static string TestHelper(this HtmlHelper helper)
{
    var controller = helper.ViewContext.RouteData.Values["controller"].ToString();
    var action = helper.ViewContext.RouteData.Values["action"].ToString();
    return controller + "/" + action;
}

If called in your Index view , it would return "Home/Index".

If called in your Partial view , it would return "Home/Partial".

Hope that helps.

Upvotes: 1

Related Questions