naz786
naz786

Reputation: 495

How to get image from the Model to be used inside View in CSS style tag?

I have a property in each object item the Model which contains the image name. I need to load each property to properly style the css for each item. I found that you can't yet access the Model in the CSS files. This is my View and attempt to use the @item.OutputImage in a style tag which doesn't seem to work:

@model IEnumerable<ValueVille.Models.CategoryViewModel>

@{
    ViewBag.Title = "Home Page";
}

@foreach (var item in Model)
{
    <style>
        #nicky-bg-top {
            background: #0197BA url("/Content/Images/@item.OutputImage") no-repeat 49.5% 0%;
            background-size: 128px 128px;
        }
    </style>
}

The content that the css class is meant to style is the third div which has the id of nicky-bg-top:

    <div class="row whiteBG">
    @foreach (var item in Model)
    {
        <div class="col-sm-3 align-centre">
            <img src="@item.OutputImage" alt="@item.Image" />
            <div class="blend-box-top" id="nicky-bg-top">
                <div class="item-container">

                    <div class="desc-plus">
                        <p>@item.Name</p>
                        <p>+</p>
                    </div>
                </div>
            </div>
        </div>
    }
</div>

Upvotes: 0

Views: 229

Answers (2)

naz786
naz786

Reputation: 495

I decided to just use multiple CSS classes in the CSS file and use them in the View like so using the model's id property:

class="blend-box-top category-head" id="[email protected]"

            <div class="blend-box-top category-head" id="[email protected]">
                <div class="item-container">

                    <div class="desc-plus">
                        <p>@item.Name</p>
                        <p>+</p>
                    </div>
                </div>
            </div>

Upvotes: 0

Marcos Silva
Marcos Silva

Reputation: 2019

You could use inline style like this:

<div style="background-image: url(/Content/Images/@item.OutputImage)">

Or, with Angular

<div style="background-image:url( {{ item.outputImage }} )" ></div>

This leave the rest of your styling in CSS

Upvotes: 1

Related Questions