'Get the very last part of a Url to use in a ternary operator
I've very new to C# and I'm using ASP.NET 6.
On a .cshtml Razor page I'm trying to use a ternary operator to fill in a HTML element class based on the very last segment of a URL pathname. So for example: On a page called localhost:7659/Identity/Account/Login I'm trying to test if a loaded URL page name has the word Login in the very last URL segment.
This is what I'm trying at present:
<a class="@Context.Request.Path == '/Login' ? 'active-page' : ''" href="/Identity/Account/Login">
But the above is rendered as
<a class="/Identity/Account/Login == '/Login' ? 'active-page-header-menu-link' : ''" href="/Identity/Account/Login">
ie the code is not being parsed out, also @Context.Request.Path
is returning the whole URL pathname, in this case, /Identity/Account/Login how can I just return the value Login?
Thanks
Solution 1:[1]
Your generated html is also not correct, you need use @(...)
in the anchor class.
Change your code to:
<a class="@(Context.Request.Path.Value.IndexOf("/Login")>-1? "active-page" : "")" href="/Identity/Account/Login">XXX</a>
Then it will generate the link if the request url last segment is Login
:
<a class="active-page" href="/Identity/Account/Login">XXX</a>
If the last segment is not Login
, it will generate the link:
<a class href="/Identity/Account/Login">XXX</a>
Solution 2:[2]
You can check if the path contains 'login', like:
Context.Request.Path.contains("Login")
Or use the below code to get the last part of the URL:
Context.Request.Path.Substring(Context.Request.Path.LastIndexOf('/') + 1)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rena |
Solution 2 | Jeremy Caney |