Reputation: 327
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?
Upvotes: 0
Views: 1012
Reputation: 35222
You can get the value of a property dynamically using reflection like this.
@for (int i = 1; i < 11; i++)
{
string imagePropName= "Image_" + i;
string imageSrc = Model.GetType().GetProperty(imagePropName).GetValue(Model) as string;
if (!string.IsNullOrEmpty(imageSrc))
{
<div>
<img src="@Url.Content(imageSrc)" />
</div>
}
}
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 your View
. If the requirement changes to displaying 20 images, you'd have to add 10 more properties.
Upvotes: 1