n.shojaei n.shojaei - 3 months ago 19
CSS Question

Dynamic background-image

I want to have multiple

div
with different background URLs.
My inline razor for this code seems to be wrong:

<table>
@foreach (var item in fa.get_albums()) {
<tr>
<td>
<div style="background-image:url('@item.picture');">
///something
</div>
</td>
</tr>
}
</table>


What's the right way to put inline razor in to
background-imag:url()
?

Answer

The issue you have is that MVC will happily fix the relative paths inside an img src attribute but not for style. You should map that virtual path using Url.Content():

<div style="background-image:url('@Url.Content(item.picture)');">