简体   繁体   中英

Inline styles and strings in MVC (Views)

I have a ViewModel named HomepageVM containing a list of strings (which hold a location to a specific file - eg "\\images\\img.png").

public class HomepageVM
{
    public List<string> Images { get; set; }
}

I am trying to insert the value of those as a background-image property using inline-styles.

@foreach (var item in Model.Images)
{
    <div style="background-image: url(@(item));"></div>
}

For some reason, the result I get inside the browser is "imagesimg.png" instead of "\\images\\img.png\\" even though the value while debugging clearly contains these slashes.

As it turns out, the solution was quite simple. Using backslashes was creating the issue where MVC seems to remove them from the output when injected into the inline styles. Replacing them with slashes as mentioned by both mason and Shyju has fixed the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM