Skip to content Skip to sidebar Skip to footer

Dynamic Html Attribute Format In Razor

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

Solution 1:

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.

Solution 2:

How about the code snippet below?

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

Solution 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.

<divclass="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))
    returnString.Empty;

returnString.Format("style=\"background-image: url('{0}')\"", GetBannerImageMediaUrl);
                          ---^                          ---^

Post a Comment for "Dynamic Html Attribute Format In Razor"