Original: Knockout 2 ways to get the index of an array element, implemented in MVC
When iterating through arrays and collections, it is common to get the index of an element, and this experience uses knockout to get an index of 2 methods.
Suppose there is a model like this:
namespace useindex.models{ publicclass Student { publicint getset;} Public string Get Set ; } }}
In HomeController, a collection of student is simulated, the collection of the Name property is projected, and the last JSON is returned to the foreground view.
usingSystem.Collections.Generic;usingSystem.Linq;usingSYSTEM.WEB.MVC;usingUseindex.models;namespaceuseindex.controllers{ Public classHomecontroller:controller { PublicActionResult Index () {returnView (); } PublicJsonresult getstudentnames () {varStudents =NewList<student>() { NewStudent () {Id =1, Name ="Xiao Ming"}, NewStudent () {Id =2, Name ="Squealing Day"} }; varNames = fromStudentinchStudentsSelect New{student. Name}; returnJson (names, jsonrequestbehavior.allowget); } }}
In the home/index.cshtml:
@{Layout=NULL;}<! DOCTYPE html>"Viewport"Content="Width=device-width"/> <title>Index</title> <script src="~/scripts/jquery-1.8.2.min.js"></script> <script src="~/scripts/knockout-2.2.0.js"></script> <script type="Text/javascript">$ (function () {varVM =NewViewModel (); Ko.applybindings (VM); Vm.init (); }); function ViewModel () {varSelf = This; Self.items=Ko.observablearray ([]); Self.showitemindex= function (item,Event) { varContext = Ko.contextfor (Event. Target);//Gets the context of the binding element; Event.target binds the DOM element of the view model varindex =context. $index (); Alert ("the current index is:"+index); }; Self.init=function () {$.getjson ('@Url. Action ("Getstudentnames", "Home")', function (data) {vararr = []; for(vari =0; i < data.length; i++) {Arr[i]=Data[i]. Name; } self.items (arr); }); }; } </script> <style type="Text/css">//style slightly</style>"Foreach:items"> <tr> <td data-bind="text: $index"></td> <TD data-bind="text: $index () + 1"></td> <TD data-bind="text: $data"></td> <td><a href="#"Data-bind="click: $root. Showitemindex"> click Show Index </a></td> </tr> </tbody> </table> </div> </body>Above, $data refers to the current collection element. $root refers to the ViewModel in the root context.
Run:
Summarize
There are 2 ways to get the index number of a collection or array element:
1, through data-bind= "text: $index" or data-bind= "text: $index () + 1"
2, in the view model through the method to obtain: first get to the context, and then context. $index ()
Knockout 2 ways to get the index of an array element, implemented in MVC