在c#代码(MVC4)中添加图像
本文关键字:添加 图像 MVC4 代码 | 更新日期: 2023-09-27 18:14:10
我试图在webgrid中加载一些if/else逻辑中的图像。本质上,如果API返回true显示其中一张图像如果返回false显示另一张图像然而我现在使用的代码-
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 ="~/Content/offstate.png">");
}
else
{
return new HtmlString("<img src =~/Content/onstate.png>");
}
}),
不能正常工作,因为每个图像返回的url是https://localhost:44300/~/Content/onstate.png和https://localhost:44300/"~/Content/offstate.png"分别当我想要的是https://localhost:44300/Content/offstate.png
(尝试删除~/出于烦恼,但这将返回https://localhost:44300/Home/Content/onstate.png,以防有人有这个想法。)
编辑:解决方案是使用Url。内容功能如下
return new HtmlString("<img src = " + Url.Content("~/Content/offstate.png") + ">");
由Ashok建议!
无论当前页面如何,您总是需要该图像的相对路径。在这种情况下,我们需要@ url content(…)。
看看为什么要使用@Url。内容主题,而不是提供路径。从@Url获取路径。内容和加入到您的html。