We are creating image tag from the programming in Sitecore 9.1.1. Using the below code.

var image = new MediaItem(imageField.MediaItem);
                    src = StringUtil.EnsurePrefix('/', MediaManager.GetMediaUrl(image));
                    string alt = image.Alt;
                    string imgTag = String.Format(@"src={0} alt={1}", src,alt);
                    model.Image = imgTag;

Adding imgTag in view

<img @Model.Image />

However , when we add single sting in Alt then it shows correctly but when we try to add string with space then it is showing like this after inspecting the image on the browser

This output is with single string

<img src="/sitecore/shell/-/media/Project/download.jpg" alt="Image" />

When we add string with space in Alt text in image then showing the below output

<img src="/sitecore/shell/-/media/Project/download.jpg" alt="Image" text/>

Here alt text is "Image text"

  • 1
    why would you try to generate an image tag in this way? Just use the field renderer, it works, and includes the alt text, and doesn't have issues like this. It will also be editable in the experience editor...
    – Richard Seal
    Sep 19 '21 at 22:45

It looks like a string formatting issue, you need to add single quotes for the string format, try to use below sample code-

string imgTag = String.Format(@"src='{0}' alt='{1}'", src,alt);

The above code has single quotes('{1}') for src and alt variables.

  • After adding this, this is showing this result <img src="'/sitecore/shell/-/media/downloaddata-image---Copy.png'" alt="'Image" text&#39;=""> Sep 19 '21 at 9:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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