user10099944
user10099944

Reputation:

How to use for loop in a Model?

I'm trying to use for loop (not foreach) on a Model but no model properties shows up when I put dot after 'Model'. Do you know why?

@model IEnumerable<JPK.Models.DocumentsModel>

@using (Html.BeginForm("Update", "Home", FormMethod.Post))
{

 @for (var i = 0; i < Model.Count(); i++)
     {
        <tr>
            <td>
                @Html.HiddenFor(modelItem => Model[i].Account )   //it doesn't work here, after Model. no properties apppear
                @Html.DisplayFor(modelItem => Model[i].Account) //same here
            </td>

            <td>
                <input type="submit" value="Save" />
            </td>
        </tr>
     }
}

Upvotes: 0

Views: 933

Answers (3)

Serge
Serge

Reputation: 43860

Try this:


@foreach (var model in Model)
     {
        <tr>
            <td>
                @Html.HiddenFor(model=> model.Account )   //it doesn't work here, after Model. no properties apppear
                @Html.DisplayFor(model=> model.Account) //same here
            </td>

            <td>
                <input type="submit" value="Save" />
            </td>
        </tr>
     }

or you can try

@model JPK.Models.DocumentsModel[]

You can still use foreach operator OR IF you want to use your index for as it is now, change count to length:

@for (var i = 0; i < Model.Length; i++)

Only before calling the view in your controller convert model to array. You can convert like this:

var model=oldModel.ToArray();
return View(model);

Upvotes: 0

You have to accept it as a List if you want to use it in a For loop. If you have to use an IEnumerable you have to use a foreach loop with a counter.

Something like this.

@{var counter = 0}
@foreach (var modelItem  in Model)
 {
    <tr>
        <td>
            @Html.HiddenFor(modelItem => modelItem.Account )   //it doesn't work here, after Model. no properties apppear
            @Html.DisplayFor(modelItem => modelItem.Account) //same here
        </td>

        <td>
            <input type="submit" value="Save" />
        </td>
    @counter++
    </tr>
 }

Or you could use var index = Model.IndexOf(modelItem)

Upvotes: 0

pwilcox
pwilcox

Reputation: 5753

Try using the 'model' parameter in your lambda, not the 'Model' object of the page:

@Html.HiddenFor(model => model[i].Account)   

Upvotes: 0

Related Questions