How to display dynamic image name using Razor

I am new to MVC and recently started the Asp.Net MVC3 project using the Razor viewer.

I am currently having problems rendering the image name in the html img tag using Razor.

Say I have a Car class in my model with a string property called ModelName. I also have a folder with images of a car model, they are named after the car model, so I can by agreement show an image of a specific model, just using the name.

From my controller, I pass the Cars collection in my opinion and will do the following to show a list of images of car models:

@foreach (var item in Model) { <img src='@item.ModelName.png' /> } 

However, if I try to run this, I get an error message:

Compiler error message: CS1061: 'string' does not contain a definition for 'png' and no extension method 'png' takes the first argument type 'string' can be found (are you missing using directive or assembly?)

I also tried

  @foreach (var item in Model) { <img src='@{item.ModelName}.png' /> } 

But this leads to:

Compiler Error Message: CS1528: Pending; or = (cannot specify constructor arguments in> declaration) Source error:

Line 84: # default line Line 85: hidden line #line 86: WriteLiteral (".png \ '"> \ \ "); Line 88:

I can get around this by doing:

 @foreach (var item in Model) { string imageName = string.Format("{0}.png", item.ModelName); <img src='@imageName' /> } 

But it seems rather awkward, of course, there must be a better way

+6
source share
2 answers

You can also do:

 @foreach (var item in Model) { <img src="@(item.ModelName).png" /> } 

Or make an assistant:

 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()); } 

and use it like:

 @foreach (var item in Model) { @Html.Image(item.ModelName) } 
+20
source
 @foreach (var item in Model._imageList) { <tr> <td> @Html.DisplayFor(modelItem => item.FriendlyName) </td> <td> @Html.DisplayFor(modelItem => item.CreateDate) </td> <td> <img src="@Url.Content(item.ImagePath)" alt="Image" /> </td> <td> @Html.ActionLink("Edit", "UploadImageEdit", new { id = item.ImageID }) | @Html.ActionLink("Details", "UploadImageDetails", new { id = item.ImageID }) | @Html.ActionLink("Delete", "UploadImageDelete", new { id = item.ImageID }) </td> </tr> } 

This will display the image saved in the file system, but the file path is saved in the database when using the foreach loop.

+2
source

Source: https://habr.com/ru/post/887897/


All Articles