@If inside a <body> tag

Asked

Viewed 576 times

2

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

While trying to make:

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

It does not perform because it does not have a tag </body> together. If it were a clause <p></p> it would work, but as the closing tag </body> can’t be together he won’t let run.

While trying to make a:

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

It’s nowhere near working.

2 answers

2


If you want to make the HTML code a little clearer, you can separate the condition into a block by part 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>

Observing: In my tests, using ASP.NET MVC 5, the attribute value does not need to be enclosed in quotes. Using bodyAttr = "class='home'" the generated HTML was <body class="'home'"> (with extra single quotes). When I use bodyAttr = "class=home" the HTML is bodyAttr = "class=home". I don’t know how the behavior in previous versions of MVC.

0

Try using the ternary operator similar to the second form:

<body @{Request.Path.Substring(Request.Path.LastIndexOf("/") + 1).ToLower() == "default" ? "class='home'" : "";}>
  • Presented the error: "; expected"

  • @Dorathoto Missing a semicolon at the end. I edited the answer.

Browser other questions tagged

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