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

2 answers

  • answered 2022-05-06 01:34 Eslam Mahfouz

    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)
    

  • answered 2022-05-06 02:03 Rena

    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>
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum