1

How can I format my own attribute in the codebehind? The idea is to overwrite CSS inline style so I added a property to my Model.

public string GetBannerBackgroundStyle
{
    get
    {
       return !string.IsNullOrEmpty(GetBannerImageMediaUrl) ? string.Format("style=background-image: url('{0}')", GetBannerImageMediaUrl) : string.Empty;
    }
}

In the view I simply set the property on the HTML

<div class="anything" @Model.GetBannerBackgroundStyle></div>

The output however is scrambled. It generates something but not properly as if the quotes weren't closed.

Any better ideas?
Thanks in advance!

UPDATE:

public HtmlString GetBannerBackgroundStyle
{
    get
    {
        return new HtmlString(!string.IsNullOrEmpty(GetBannerImageMediaUrl) ? string.Format("style=background-image: url('{0}')", GetBannerImageMediaUrl) : string.Empty);
    }
}

This didn't seem to work :s

UPDATE2:

public IHtmlString GetBannerBackgroundStyle
{
    get
    {
        return new HtmlString(!string.IsNullOrEmpty(GetBannerImageMediaUrl) ? string.Format("style=\"background-image: url('{0}')\"", GetBannerImageMediaUrl) : string.Empty);
    }
}

This did work ^^

5
  • Please note that your string does not have quotes, so not sure what you actually expect - "style=background-image: url('{0}')". Also to improve sample code consider replacing GetBannerImageMediaUrl with inline string constant (like string BannerImageMediaUrl="/foo/bar.jpg"; that matches your string). and possibly expected/actual output instead of "didn't seem to work:s". Commented Oct 29, 2014 at 14:35
  • @Alexei I thought HTML would "correct" the quotes but that doesn't seem to happen. Hence I had to escape them as Adriano suggests in his answer. The default image is on CSS level. I only needed an attribute if the image is not null. This to avoid unnecessary inline style. Commented Oct 29, 2014 at 14:40
  • 1
    Tim Vermaelen, I think you are talking about ability to omit quotes for attributes in HTML and indeed it is possible for most cases. But "style" have to have them as it contains more than just alphanumeric values - see w3.org/TR/1999/REC-html401-19991224/intro/sgmltut.html#h-3.2.2 Commented Oct 29, 2014 at 14:45
  • Hence I've tried it with single quotes but that didn't seem to work. It's Razor that's the second player in this problem. Webforms is probably gonna be just fine the way I tried at first. Commented Oct 29, 2014 at 14:50
  • Single quotes would work fine - as long as you've remove them from url(... in the style where they are optional - "style='background-image: url({0})'". Commented Oct 29, 2014 at 14:53

3 Answers 3

3

From MSDN:

The Razor syntax @ operator HTML-encodes text before rendering it to the HTTP response. This causes the text to be displayed as regular text in the web page instead of being interpreted as HTML markup.

That's where you can use Html.Raw method (if you don't want/can't change your property to return an HtmlString, please remember that right way to do it is that one as suggested by SLaks):

Use the Raw method when the specified text represents an actual HTML fragment that should not be encoded and that you want to render as markup to the HTTP response.

<div class="anything" @Html.Raw(Model.GetBannerBackgroundStyle)></div>

That said I wouldn't put that logic inside your model. An helper method, some JavaScript...but I wouldn't mix styling with data. In your example it should be:

<div class="anything"
    style="background-image: url('@Model.GetBannerImageMediaUrl')">

Please note that your code was also wrong because you're missing quotes for HTML style attribute:

if (!String.IsNullOrEmpty(GetBannerImageMediaUrl))
    return String.Empty;

return String.Format("style=\"background-image: url('{0}')\"", GetBannerImageMediaUrl);
                          ---^                          ---^
Sign up to request clarification or add additional context in comments.

1 Comment

It was indeed the quotes. Thought I had tried it before but probably not 100% as I did try many things with @, ', " and \".
3

You need to make your property return an IHtmlString to tell Razor to not escape it.

First, however, you need to properly escape it yourself, in case the URL has tags or quotes.

3 Comments

new HtmlString(text)
It didn't work :s I'll update my answer with what I've tried.
@TimVermaelen: How doesn't it work? What happens?
3

How about the code snippet below?

<div class="anything" @(Model != null && !string.IsNullOrWhiteSpace(GetBannerImageMediaUrl) 
? "style=background-image: url('" + GetBannerImageMediaUrl + "')" 
 : string.Empty)></div>

1 Comment

I really wanted to avoid this kind of tricks, thanks for the attempt tho ^^

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.