IF condition within _Layout.cshtml in MVC

Posted on

Question :

I have two _Shared.cshtml (MVC masterpage type, I do not know the name) and both are pretty much the same, only the left menu is different.

I would like to do only 1 and according to the querystring I will call the page I want to be the menu: ex

@if (Request.FilePath.Contains("Home")) 
@ { $("#IDMenu").load('menu_Home.html'); }
@ else
@ { $("#IDMenu").load('menu_Admin.html'); } 

More or less so.

Basically today my application has 2 url

localhost: 47123 / home /

or

localhost: 47123 / Admin /

If it’s Admin I want it to call menu_admin.html if it’s home it will call another page.

I do not know how to use the Razors.

    

Answer :

Assuming you want to write JavaScript code through Razor to be interpreted on the client side, you can use the <text> tag:

<script type="text/javascript">

//código JavaScript

@if (Request.FilePath.Contains("Home")) {
    <text>
    $("#IDMenu").load('menu_Home.html');
    //mais código JavaScript
    </text>
} else {
    <text>
    $("#IDMenu").load('menu_Admin.html');
    //mais código JavaScript
    </text>
}

//código JavaScript

</script>

There’s more on this in this other OS issue

    

You had an easier way to do this. How?

If only the menu on the left changes, just put before the menu:

@if (User.Identity.IsAuthenticated)
{
    if (Roles.IsUserInRole("Admin"))
    {
        //MENU DA ESQUERDA PARA ADMIN
    }
}   
@if (User.Identity.IsAuthenticated)
{
    if (Roles.IsUserInRole("Home"))
    {
        //MENU DA ESQUERDA PARA Home
    }
}

I would do so. Although I also find the answer from @carlosrafaelgn simple and with less “confusion” code in the same Partial

EDIT
I noticed now that you wanted the URL to change too, this example I put does not solve this. I’ll leave the same in the answer, it may be useful for cases of restricting access

    

Leave a Reply

Your email address will not be published. Required fields are marked *