asp.net-mvc – 如何在MVC WebGrid中显示行号

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 如何在MVC WebGrid中显示行号前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在MVC WebGrid中有一个列作为行号.我该怎么做?

解决方法

您可以使用包含指示行号的属性的视图模型.

假设您有以下域模型:

  1. public class DomainModel
  2. {
  3. public string Foo { get; set; }
  4. }

现在,您构建一个与视图要求相对应的视图模型:

  1. public class Myviewmodel
  2. {
  3. public int RowNumber { get; set; }
  4. public string Foo { get; set; }
  5. }

接着:

  1. public ActionResult Index()
  2. {
  3. // fetch the domain model from somewhere
  4. var domain = Enumerable.Range(1,5).Select(x => new DomainModel
  5. {
  6. Foo = "foo " + x
  7. });
  8.  
  9. // now build the view model
  10. // TODO: use AutoMapper to perform this mapping
  11. var model = domain.Select((element,index) => new Myviewmodel
  12. {
  13. RowNumber = index + 1,Foo = element.Foo
  14. });
  15.  
  16. return View(model);
  17. }

现在,您的视图将成为视图模型的强类型:

  1. @model IEnumerable<Myviewmodel>
  2.  
  3. @{
  4. var grid = new WebGrid(Model);
  5. }
  6.  
  7. @grid.GetHtml(
  8. columns: grid.Columns(
  9. grid.Column("RowNumber"),grid.Column("Foo")
  10. )
  11. )

现在让我们假设你出于某些愚蠢的原因不想使用视图模型.在这种情况下,如果您愿意,可以将视图转换为意大利面条代码

  1. @model IEnumerable<DomainModel>
  2.  
  3. @{
  4. var grid = new WebGrid(Model.Select((element,index) => new { element,index }));
  5. }
  6.  
  7. @grid.GetHtml(
  8. columns: grid.Columns(
  9. grid.Column("RowNumber",format: item => item.index + 1),grid.Column("Foo",format: item => item.element.Foo)
  10. )
  11. )

猜你在找的asp.Net相关文章