1

I am trying to add an image in the div style property, above which some text would be shown, Below is the code I wrote :

<div class="c-tile -red " style="background-image:url(@Html.Sitecore().Field("KfcStartContent_Img3"));">
  <div class="c-tile__icon" style="background- image:url(@Html.Sitecore().Field("KfcStartContent_Img3"));">
<p class="c-heading -plus-x -secret-number"><small># 
</small>8-11</p>
  </div>
  <div class="c-tile__text">
    <p class="c-heading -plus-x -secret-number"><small># 
    </small>8-11</p>
    <h3 class="c-heading -plus-x" style="color:black;">@Html.Sitecore().Field("KfcStartContent_Img3_Details") 
    </h3>
  </div>
</div>

Which should have given the output as below : enter image description here

But it is showing like this : enter image description here When I checked in developer tools, instead of just an url of image, some hash code is generated, by which my css styling are getting disabled and not showing the image .

enter image description here

I have used View rendering.

0

2 Answers 2

4

You cannot just assign image field value as a background image. You have to first get the src of the image like:

@{
    ImageField imageField = item.Fields["KfcStartContent_Img3"];
    string url = Sitecore.Resources.Media.MediaManager.GetMediaUrl(imageField.MediaItem);
}

and then use it like:

<div class="c-tile-red " style="background-image:url(@url);">

You can read more here: https://community.sitecore.net/developers/f/8/t/1107

0
0
    public static string ImageUrl(this Item item, ID imageFieldId, MediaUrlOptions options = null)
    {
        if (item == null)
        {
            throw new ArgumentNullException(nameof(item));
        }

        var imageField = (ImageField)item.Fields[imageFieldId];
        return imageField?.MediaItem == null ? string.Empty : imageField.ImageUrl(options);
    }

With the help of above code block you can get the image url and store in model in your backend code, and pass main model to view then you can mentioned image url in the CSS

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.