Miguel Moura
Miguel Moura

Reputation: 39454

Conditional HTML tag on Body tag

On an ASP.NET Core 2.1 view I have the following:

<div @{if (1==1) { <text>style="background-image: url('image.png')"</text> }}></div>

Note: I am using 1==1 just for testing ...

This renders fine but I need to apply this to body tag:

<body @{if (1==1) { <text>style="background-image: url('image.png')"</text> }}>

In this case I get the error:

The tag helper 'body' must not have C# in the element's attribute declaration area.

How to solve this?

Upvotes: 0

Views: 1380

Answers (1)

John-Luke Laue
John-Luke Laue

Reputation: 3856

What you are writing doesn't seem to result in valid HTML.

Here are a few ideas (in order of complexity) to get you started.

Traditional conditional

<body>
    @if (1 == 1)
    {
        <div style="background-image: url('image.png')"></div>
    }
    else
    {
        <div></div>
    }
</body>

Ternary Operator

<div style="@((1 == 1) ? "background-image: url('image.png')" : "")"></div>

Move logic to separate block

@{
    var divStyle = "";
    if (1 == 1)
    {
        divStyle = "background-image: url('image.png')";
    }
}

<div style="@divStyle"></div>

Logic done server side and stored in model

@model MyViewModel

<div style="@Model.DivStyle"></div>

Inject service into View (Dependency Injection)

@inject StyleService _styleService

<div style="@_styleService.GetStyleIfTrue(1 == 1)"></div>

Upvotes: 3

Related Questions