How to display row number in MVC WebGrid

I want to have a column as row number in MVC WebGrid. How can i do this?

+4
source share
5 answers

You can use a view model that will contain a property indicating the line number.

Suppose you have the following domain model:

 public class DomainModel { public string Foo { get; set; } } 

Now you are creating a view model that will meet the requirements of your view:

 public class MyViewModel { public int RowNumber { get; set; } public string Foo { get; set; } } 

and then:

 public ActionResult Index() { // fetch the domain model from somewhere var domain = Enumerable.Range(1, 5).Select(x => new DomainModel { Foo = "foo " + x }); // now build the view model // TODO: use AutoMapper to perform this mapping var model = domain.Select((element, index) => new MyViewModel { RowNumber = index + 1, Foo = element.Foo }); return View(model); } 

Now your view will be strongly typed on the view model:

 @model IEnumerable<MyViewModel> @{ var grid = new WebGrid(Model); } @grid.GetHtml( columns: grid.Columns( grid.Column("RowNumber"), grid.Column("Foo") ) ) 

Now suppose that for some stupid reason you do not want to use presentation models. In this case, you can put your view in spaghetti code if you want:

 @model IEnumerable<DomainModel> @{ var grid = new WebGrid(Model.Select((element, index) => new { element, index })); } @grid.GetHtml( columns: grid.Columns( grid.Column("RowNumber", format: item => item.index + 1), grid.Column("Foo", format: item => item.element.Foo) ) ) 
+9
source

This is a really good approach, but when using sorting or swapping, RowNumber values ​​do not start at 1 per page.

In my project, I had a case where I needed to know the row index regardless of WebGrid swap / sort, and I came across the following solution:

 grid.Column( Header: "RowNumber", Format: item => item.WebGrid.Rows.IndexOf(item) + 1 ) 
+11
source
  @{ int i=0; foreach (var item in Model) { <tr> <td> @i </td> <td> @Html.DisplayFor(modelItem => item.Expense) </td> <td> @Html.ActionLink("Edit", "Edit", new { id=item.Id }) | @Html.ActionLink("Delete", "Delete", new { id = item.Id }, new { onclick = "return confirm('Are you sure you wish to delete this record?');" }) </td> </tr> i++; } } 

Try

+4
source

just add the following code

 grid.Column(header: "No." ,format: item => item.WebGrid.Rows.IndexOf(item) + 1 + Math.Round(Convert.ToDouble(grid.TotalRowCount / grid.PageCount) / grid.RowsPerPage) * grid.RowsPerPage * grid.PageIndex) 

Check out this link for more information.

hope it will be useful for someone

+4
source

Add this:

 grid.Column(header: "No.", format: item => item.WebGrid.Rows.IndexOf(item) + 1 + Math.Round(Convert.ToDouble(grid.TotalRowCount / grid.PageCount) / grid.RowsPerPage) * grid.RowsPerPage * grid.PageIndex) 
-1
source

All Articles