I'm rather new to MVC and have recently started a Asp.Net MVC3 project, using the Razor view engine.
At the moment I'm having trouble with outputting an image name into an html img tag with Razor.
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:
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?)
I also tried
@foreach (var item in Model) {
<img src='@{item.ModelName}.png' />
}
But that results in:
Compiler Error Message: CS1528: Expected ; or = (cannot specify constructor arguments in >declaration) Source Error:
Line 84: #line default Line 85: #line hidden Line 86: WriteLiteral(".png\' ">\r\n"); Line 88:
I can get around it by doing:
@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??