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
How to Run Visual Studio Without Plugin and All Third Party Feature
How to Implement a Custom Razorviewengine to Find Views in Non-Standard Locations
Where's the Datetime 'Z' Format Specifier
Why Is Array.Length an Int, and Not an Uint
How to Split a String by Strings and Include the Delimiters Using .Net
How to Protect Resources That May Be Used in a Multi-Threaded or Async Environment
"There Was an Error Running the Selected Code Generator" in VS 2013 Scaffolding
"Parameter Not Valid" Exception Loading System.Drawing.Image
Play and Wait for Animation/Animator to Finish Playing
Registering a Custom JSONconverter Globally in JSON.Net
Why Is Ushort + Ushort Equal to Int
Change Sender Address When Sending Mail Through Gmail in C#
Using Itextsharp to Extract and Update Links in an Existing PDF
How to Set the Default Xml Namespace for an Xdocument