ASP.NET MVC使用Knockout获取数组元素索引的2种方法

在遍历数组、集合的时候,通常要获取元素的索引,本篇体验使用Knockout获取索引的2种方法。

假设有这样的一个模型:

namespace UseIndex.Models
{
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

在HomeController中,先模拟一个Student的集合,在投影出Name属性的集合,最后以Json返回给前台视图。

using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using UseIndex.Models;

namespace UseIndex.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public JsonResult GetStudentNames() 
        {
            var students = new List()
            {
                new Student(){Id = 1, Name = "小明"},
                new Student(){Id = 2, Name = "啸天"}
            };

            var names = from student in students
                select new {student.Name};
            return Json(names, JsonRequestBehavior.AllowGet);
        }

    }
}

在Home/Index.cshtml中:

@{
    Layout = null;
}





    
    Index
    
    
    
    


    
索引 编号 名称 在View Model中的索引
点击显示索引

以上,$data是指当前集合元素。$root是指根context中的ViewModel。

运行:

ASP.NET MVC使用Knockout获取数组元素索引的2种方法_第1张图片

总结

获取集合或数组元素的索引有2种方式:
1、通过data-bind="text: $index"或data-bind="text: $index() + 1"
2、在View Model中通过方法来获得:先获取到上下文,再context.$index()

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对脚本之家的支持。如果你想了解更多相关内容请查看下面相关链接

你可能感兴趣的:(ASP.NET MVC使用Knockout获取数组元素索引的2种方法)