john doe
john doe

Reputation: 9662

Concatenating the Razor Variables with CSS Styles

I am trying to concatenate the Razor Variable (int) with a CSS Style so I can display the background image.

@{
    var positionY = 0; 
}

@foreach (var img in Model.Images)
{
    <div style="background-image: url('@Model.SpriteSheetUrl'); width: 60px; height: 60px;background-position: 0px @positionY px)> </div>



    positionY += 60; 

}

The problem I am facing is with the following line:

@positionY px

This produces 60 px (Notice the space between 60 and px) That space is causing the issue. How can I eliminate that space so it reads 60px instead of 60 px.

Upvotes: 2

Views: 4462

Answers (2)

Charlie B
Charlie B

Reputation: 11

Another scenario where the model property is only part of the url and must be preceded by an extension. The escape character must be used to concatenate the extension.

<div style="color:white;text-align:center;width:24px;background-image:url('../../images/@item.Color\.png'); background-repeat:no-repeat;background-position:left;background-size:100%;">

Upvotes: 0

Matthew Jones
Matthew Jones

Reputation: 26190

Try this:

<div style="background-image: url('@Model.SpriteSheetUrl'); width: 60px; height: 60px;background-position: 0px @(positionY + "px"))> </div>

The @() renders whatever is written inside of it as a literal, so you should get "60px" as the output.

Upvotes: 10

Related Questions