您现在的位置是:网站首页> 编程资料编程资料
ASP.NET MVC使用Knockout获取数组元素索引的2种方法_实用技巧_
2023-05-24
272人已围观
简介 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。
运行:

总结
获取集合或数组元素的索引有2种方式:
1、通过data-bind="text: $index"或data-bind="text: $index() + 1"
2、在View Model中通过方法来获得:先获取到上下文,再context.$index()
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接
您可能感兴趣的文章:
相关内容
- .NET Smobiler的复杂控件的由来与创造_ASP.NET_
- ASP.NET MVC为用户创建专属文件夹_实用技巧_
- ASP.NET MVC实现多选下拉框保存并显示_实用技巧_
- ASP.NET MVC打印表格并实现部分视图表格打印_实用技巧_
- ASP.NET Core 6最小API中使用日志和DI示例详解_ASP.NET_
- ASP.NET MVC实现路由功能_实用技巧_
- ASP.NET MVC创建XML文件并实现元素增删改_实用技巧_
- ASP.NET MVC下拉框中显示枚举项_实用技巧_
- ASP.NET MVC把表格导出到Excel_实用技巧_
- 详解ASP.NET中加密和解密的方法_实用技巧_
