0

I have a foreach loop within my MVC view cycling through my model, and in it a separate div element is rendered for each object in my list. Now, I want the background of this object to be an image with 50% opacity. The image is not the same for iteration of the loop, however, and will depend on one of the parameters of the model object.

To make it clearer, currently I have:

@foreach (var itm in Model)
{    
    <div id="shell" style="position: relative; etc....">
       Many other div elements placed with position: absolute within the shell container.
    </div>
}

The name of the image within my content folder can be found by itm.Company + jpeg, and I want to make this the background image of the div with opacity: 0.5;

I found out here that I can't merely set the background image to the shell div because then I can't change it's opacity without changing the entire div's opacity.

The following answer states I should create it by including another div like:

HTML

<div class="myDiv">
    <div class="bg"></div>
    Hi there
</div>

CSS

.myDiv {
    position: relative;
    z-index: 1;
}

.myDiv .bg {
  position: absolute;
    z-index: -1;
    top: 0;
        bottom: 0;
    left: 0;
    right: 0;
    background: url(test.jpg) center center;
    opacity: .4;
    width: 100%;
    height: 100%;
}

I tried this:

@foreach (var itm in Model)
{    
    <div id="shell" style="z-index: 1; position: relative; etc....">
        <div class="companyImage" style="z-index:-1; top: 0; bottom: 0; left: 0; right: 0; background: url(~/Content/images/@(itm.Company).jpeg);">                                                                            
        </div>
        Many other div elements placed with position: absolute within the shell container.
    </div>    
}

However, the razor within the url() part of my companyImage div's style sheet doesn't render properly. I get no error, but the highlighting in VS disappears and it does nothing.

So does anyone know the best way of setting the background image of a div element, with 50% opacity, taking into account that I need to change the image name on each iteration of my foreach loop?

Community
  • 1
  • 1
JonnyKnottsvill
  • 1,123
  • 2
  • 16
  • 39
  • Can you make a JSFiddle(https://jsfiddle.net/ ) of the scenario? – apohl Nov 04 '15 at 16:54
  • This http://jsfiddle.net/sbGb4/2/ which I credit to @MarkusEkwall is his example. And that's what I want, but I need to insert into the url the itm.Company string. – JonnyKnottsvill Nov 04 '15 at 16:58

1 Answers1

0

The problem seems to be your url, since you are passing the variable as a raw string, the url is literally url(~/Content/images/@(itm.Company).jpeg), and not the value of your itm.Company. To do that you must use something in the lines of the following code:

...url(~/Content/images/"+@itm.Company+".jpeg);"

So that itm.Company is interpreted as C# code.

Pedro Figueiredo
  • 2,304
  • 1
  • 11
  • 18