IF condition inside _Layout.cshtml in MVC

Asked

Viewed 2,764 times

3

I have two _Shared.cshtml (MVC masterpage type, do not know the name) and both are virtually equal, only the menu left 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'); } 

Something like that.

Basically today my application has 2 url

localhost:47123/home/

or

localhost:47123/Admin/

If you are Admin I want you to call menu_admin.html if you are home will call another page.

I don’t know how to use the Razors.

2 answers

2


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

<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 to this subject in this another issue of the OS

  • what would be this <text> tag? I’ll test, but it looks like that’s it

  • 1

    That tag <text> serve to send to the client all the text that is between <text> and </text>, untouched by the server ;)

  • another detail.my url http://localhost:47123/Home/contacts_view? id=1 @if (Request.QueryString.Allkeys.Contains("Home")) { esta dando false, was not supposed to find?

  • Actually, no. Because his QueryString, in that case, and only id=1. However, the property Request.Path would return to you "/Home/contatos_visualizar"

0

You had an easier way of doing that. How?

If only the menu on the left changes, just put it 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 @carlosrafaelgn answer simple and with less code "confusion" in the same Partial

EDIT I just noticed that you wanted the URL to change too, this example I put up does not solve that. I will still leave the answer, can be useful for cases of restricting access

Browser other questions tagged

You are not signed in. Login or sign up in order to post.