@If inside a body tag

2

How to put a if condition inside a <body> tag?

When trying to do:

@if (Request.Path.Substring(Request.Path.LastIndexOf("/") + 1).ToLower() == "default") {
    <body class="home"
} else {
    <body>
}

It does not run because it does not have a </body> tag together. If it were a <p></p> clause it would work, but since the closing tag </body> can not be together it does not let it execute.

When trying to make one:

<body @if (Request.Path.Substring(Request.Path.LastIndexOf("/") + 1).ToLower() == "default") { Response.Write("class='home'"); } >

It also does not even come close to wanting to work.

    
asked by anonymous 21.05.2015 / 19:16

2 answers

2

If you want to make the HTML code a bit clearer, you can separate the condition into a separate block and declare a variable in it with the attribute value:

@{ 
    string bodyAttr = String.Empty;
    if(Request.Path.Substring(Request.Path.LastIndexOf("/") + 1).ToLower() == "default")
        bodyAttr = "class=home";        
}
<body @bodyAttr>

Note : In my tests, using ASP.NET MVC 5, the value of the attribute does not have to be enclosed in quotation marks. Using bodyAttr = "class='home'" the generated HTML was <body class="'home'"> ( plus single quotes ). When I use bodyAttr = "class=home" the HTML is bodyAttr = "class=home" . I do not know how the behavior in earlier versions of MVC is.

    
21.05.2015 / 22:29
0

Try using the ternary operator similarly to the second form:

<body @{Request.Path.Substring(Request.Path.LastIndexOf("/") + 1).ToLower() == "default" ? "class='home'" : "";}>
    
21.05.2015 / 20:47