AndreyAkinshin / knockout-mvc

Power of Knockout.js for ASP.NET MVC
http://knockoutmvc.com
203 stars 125 forks source link

Access current record in Foreach #51

Closed afmorris closed 7 years ago

afmorris commented 9 years ago

Background Information:

I am trying to pass in the current collection iteration's model value as a parameter to an action method in a controller.

More Details:

While working with a collection, I am iterating over the collection with the following code snippet:

@using (var players = ko.Foreach(x => x.BenchPlayers))
{
    <tr>
        <td @players.Bind.Text(x => x.Name) class="vert-align"></td>
        ...
        <td class="vert-align">@ko.Html.Button("Put in Game", "PutInGame", "Home", new { player = players.Model }, new { @class = "btn btn-primary" })</td>
    </tr>
}

I am attempting to access the current iteration's Model value, but I am unsuccessful. The Model property appears to just be a new instance of the class it represents.

Is there a way to access the current iteration of the foreach loop, for the purposes of passing it to the routeValues collection, for use in the action method in the controller? If need be, I can just use a property of the object, rather than the entire object, but I'd rather use the entire object.

afmorris commented 9 years ago

To follow-up, instead of accessing the current record's model value, I am instead accessing the index of the current record and passing that through to the action method.

@ko.Html.Button("Put in Game", "PutInGame", "Home", new { index = players.GetIndex() }, new { @class = "btn btn-info" })

Then, in my action method, I access the record via the collection's accessor.

This isn't ideal, but it works in my case. Is there any other way around this?