HTML.DisplayFor method using string

866 views Asked by At

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?

1

There are 1 answers

1
adiga On BEST ANSWER

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.