In my ASP.Net MVC appication I have a loop which i'd like to display different Properties values in HTML using the HTML.DisplayFor method. But it will not accept a string value to direct to the Model parameter.
Normal mode:
<img src="@Html.DisplayFor(model => model.Image_1)" />
My loop:
@for (int i = 1; i < 11; i++)
{
string currentImage = "Model.Image_" + i;
if ((@Html.DisplayFor(model => "Model.Image_" + i ).ToString()) != "")
{
<div>
<img src="@Html.DisplayFor(model => currentImage)" />
</div>
}
}
My results in the img src
are just currentImage
.
I'd like it to be Model.Image_" + i
.
How would I do that?
If you have a better way of doing this that would be appreciated as well. Should my images have their own Model -class, you think?
You can get the value of a property dynamically using reflection like this.
Another alternative would be to write
<img src="@Url.Content(Model.Image_1)
,<img src="@Url.Content(Model.Image_2) />
10 times. I mean if you have created 10 properties, might as well be consistent with the implementation.But as stephen said, just get a
List
of ImagePaths and loop through them in yourView
. If the requirement changes to displaying 20 images, you'd have to add 10 more properties.