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 ^^
"style=background-image: url('{0}')". Also to improve sample code consider replacingGetBannerImageMediaUrlwith inline string constant (likestring BannerImageMediaUrl="/foo/bar.jpg";that matches your string). and possibly expected/actual output instead of "didn't seem to work:s".null. This to avoid unnecessary inline style.url(...in the style where they are optional - "style='background-image: url({0})'".