How to Get Current Page Url in MVC 3

How to get current page URL in MVC 3

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

Get page URL from markup in Razor Pages

This will bring the current page url:

@Url.RouteUrl(ViewContext.RouteData.Values);

[UPDATE]

The above implementation will return current page url without QueryString values e.g. /Users/Index

To include QueryString values after ? use below implementation:

@{
var routeUrl = Url.RouteUrl(ViewContext.RouteData.Values);
var qsPath = ViewContext.HttpContext.Request.QueryString.Value;
var returnUrl = $"{routeUrl}{qsPath}";
}

The end result will include route and query string values:

// returnUrl = "/Users/Index?p=1&s=5"

Get URL of actual page in MVC Controller

Just a thought (if I understand your question correctly, apologies if not):

In your layout page contact form, add two hidden inputs to pass in and use:

<input type="hidden" name="currentAction" value="@ViewContext.RouteData.Values["Action"].ToString()">

<input type="hidden" id="currentController" value="@ViewContext.RouteData.Values["Controller"].ToString()">

this will give you the exact controller and action served even though your form is located on the shared layout view

Getting the current URL within the View layer in ASP.net MVC

It probably isn't the best idea, in my opinion, to use the URL for this.

Instead, a quick and easy way to achieve this is to use ViewContext.RouteData that will contain values for both the controller and action of the current request. It can be accessed from the view layer easily.

ViewContext.RouteData.Values["Controller"].ToString()
ViewContext.RouteData.Values["Action"].ToString()

So in your view you could do something like

<ul class="nav">
<li class="@(ViewContext.RouteData.Values["Controller"].ToString() == "ControllerName" ? "active" : "")"><a href="#">Foo</a></li>
</ul>

You could push it further to make it prettier, but you get the basic idea.



Related Topics



Leave a reply



Submit