如何使用Razor显示动态图像名称 [英] How to display an dynamic image name with Razor
问题描述
我对MVC很新,并且最近使用Razor视图引擎启动了Asp.Net MVC3项目。
I'm rather new to MVC and have recently started a Asp.Net MVC3 project, using the Razor view engine.
目前我遇到了麻烦将图像名称输出到带有Razor的html img标记中。
At the moment I'm having trouble with outputting an image name into an html img tag with Razor.
假设我的模型中有一个Car类,其字符串属性名为ModelName。我还有一个包含汽车模型图像的文件夹,它们以汽车模型命名,因此我可以按照惯例通过使用名称显示特定模型的图像。
Say I have a Car class in my model, with a string property called ModelName. I also have a folder with images of the car model, they are named after the car model so that I can by convention show the image of a specific model, by just using the name.
从我的控制器中,我将一系列汽车传递给我的视图并执行以下操作以显示汽车模型图像列表:
From my controller I pass down a collection of Cars to my view and do the following to show a list of car model images:
@foreach (var item in Model) {
<img src='@item.ModelName.png' />
}
但是如果我尝试运行它,我会收到错误:
However if I try to run this, I get the error:
编译器错误消息:CS1061:
'string'不包含'png'的定义
且没有扩展方法
'peng'接受
类型'string'的第一个参数可以找到(你是
缺少using指令还是
汇编引用?)
Compiler Error Message: CS1061: 'string' does not contain a definition for 'png' and no extension method 'png' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
我也试过
@foreach (var item in Model) {
<img src='@{item.ModelName}.png' />
}
但结果是:
编译器错误消息:CS1528:预期;或=(不能在>声明中指定构造函数参数)
源错误:
Compiler Error Message: CS1528: Expected ; or = (cannot specify constructor arguments in >declaration) Source Error:
第84行:#line默认
第85行:#line hidden Line
86:WriteLiteral(。png \'
> \\\\ n);第88行:
Line 84: #line default Line 85: #line hidden Line 86: WriteLiteral(".png\' ">\r\n"); Line 88:
我可以这样做:
@foreach (var item in Model) {
string imageName = string.Format("{0}.png", item.ModelName);
<img src='@imageName' />
}
但这感觉很笨重,肯定有一个更好的方法吗?
But that feels quite clunky, surely there must be a better way??
推荐答案
你也可以这样做:
@foreach (var item in Model)
{
<img src="@(item.ModelName).png" />
}
或者做一个助手:
public static MVCHtmlString Image<T>(this HtmlHelper helper, string name)
{
TagBuilder img=new TagBuilder("img");
img.Attributes.Add("src", name+".png");
return new MvcHtmlString(img.ToString());
}
并使用它:
@foreach (var item in Model)
{
@Html.Image(item.ModelName)
}
这篇关于如何使用Razor显示动态图像名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!