1

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!

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for turning me on to that function!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.