Ben Hili Ben Hili - 1 month ago 6
ASP.NET (C#) Question

Adding an image within C# code (MVC4)

I'm trying to load an image within a webgrid within some if/else logic. Essentially if the API returns true show one image if false show the other image however the code I'm using right now -

columns: grid.Columns(
grid.Column("PowerState", format: (vm) =>
{
if (vm.PowerState == "Stopped") //Choose font colour depending on the status of the VM
{
return new HtmlString("<img src =&quot;~/Content/offstate.png&quot;>");
}

else
{
return new HtmlString("<img src =~/Content/onstate.png>");
}
}),


isn't working as intended as the URLs returned by each image are https://localhost:44300/~/Content/onstate.png and https://localhost:44300/"~/Content/offstate.png"
respectively when what I want is https://localhost:44300/Content/offstate.png

(tried removing the ~/ out of annoyance but this will return https://localhost:44300/Home/Content/onstate.png just in case somebody has that idea.)

EDIT: The solution is to use the Url.Content function as so

return new HtmlString("<img src = " + Url.Content("~/Content/offstate.png") + ">");


As suggested by Ashok!

Answer

You always need relative path to that image irrespective of current page. In such cases we need @Url.Content(...).

Look at why use @Url.Content topic and instead of providing path. Get path from @Url.Content and join to you html.