0

in my list of objects i have few similar properties.

week1 week2 week3 week4 week5 ...

I would like to be able to display them in a table based on the selected number of weeks by the user.

My idea was to use the loop like below, but i can't add "i" to the @data.week#number

  @for (var i = 0; i < Model.numberOfWeeks; i++)
                        {
                      <td>@[email protected]</td>
                        }

Is there a way i can use the incrementation of "i" to add it to the object name ?

1
  • NO, property names are static and not dynamic likewise you are expecting Commented Jun 12, 2017 at 8:48

2 Answers 2

2

You can't use variables to construct variable names. The names must remain static. If you really need that there is reflection, but that is not the best option.

Use a dictionary or list instead, so that @data.weeks[@i].name would work.

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

Comments

1

Why do you have properties as values? Anyhow, if you really need to iterate properties and output their values you can try to use reflection:

 <td>@(data.GetType().GetProperty("week" + i).GetValue(data, null))</td>

But this is a bad practice. I would strongly recommend to change your data object and a view model.

3 Comments

I don't think it is a good idea to use Reflection inside your views.
Patrick, this is possible, since Adrian wanted to know how to print properties. Another question is that this is a bad practice and should not be used in views. We just don't know why he needs this and why his data model has properties as values.
Thank you both for your suggestions, i decided to use dictionary as suggested by Patrick, which solved the issue for me.

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.