Xaxum
Xaxum

Reputation: 3675

Appending variable in for loop to mvc4 razor helper

I have a number of fields in my model which are named as such model.var_1, model.var_2, ... model.var_30.

I am trying to put these in a table so I am using a for loop as so.

<table>
            <tr>
                <th>Category</th>
                <th>Description</th>
                @for (int i = 1; i <= Model.Total; i++)
                {
                    <th class="ali_day@(i)">Day @i</th>
                }
            </tr>
            <tr>
                <th>Intubated</th>
                <th></th>
                @for (int i = 1; i <= Model.Total; i++)
                {
                <th>@Html.EditorFor(model => model.var_@(i))
                    @Html.ValidationMessageFor(model => model.var_@(i))</th>
                }
            </tr>
        </table>

However, var_@(i) doesn't seem to be valid. Is there a way to append this loop counter so I can get my variable name while using an html helper?

Upvotes: 0

Views: 270

Answers (1)

asymptoticFault
asymptoticFault

Reputation: 4529

Use the editor helper overload that takes a string, that way you can use string concatenation to create the variable name.

@Html.Editor("var_" + i)

and the same for the validation message

@Html.ValidationMessage("var_" + i)

Upvotes: 1

Related Questions