0

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?

3
  • Delete the if block (that makes no sense) and just use string currentImage = "Image_" + i; <img src="@Html.Display(currentImage)" /> but all this suggests a design problem. You should have a IEnumerable<string> Images property containing the image paths Commented Sep 7, 2017 at 10:57
  • The if block is to not add HTML if the property would be empty ( "" ). Thank you for the ideas Commented Sep 7, 2017 at 11:27
  • You clearly have a major design flaw if you really have properties Image_1, Image_2 etc Commented Sep 7, 2017 at 11:29

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you that is billiant! Solved and +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.