Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I change <img src=""> value conditionally? | Razor CSHTML

I’d like to set the src value to ImgLink if the number of elements in my iList is >= 7
and set it to an empty string if not.

I tried this

<div><img src=@Model.SlideshowItems.Count >= 7 ? "@UrlResolver.Current.GetUrl(Model.SlideshowItems[6].ImgLink)" : ""></div>

But this error shows up:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can do something like:

@{
    string src = "img/exampleDefault.png";
    if (//logic)
    {
        src = "img/example2.png";
    }
}

<div><img src=@src></div>

you can reduce the logic to one line:

@{
    string src = //logic ? "img/example1.png" : "img/example2.png";
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading