2

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.

0

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much! I will accept your answer in few minutes when StackOverFlow allows me :) Thanks again!
Are you sure you mean "literal"? positionY is not a literal but a variable.
0

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%;">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.