How to display row number in MVC WebGrid

前端 未结 5 2084
南笙
南笙 2021-01-03 07:15

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

5条回答
  •  太阳男子
    2021-01-03 07:38

    You could use a view model that will contain a property indicating the row number.

    Let's suppose that you have the following domain model:

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

    Now you build a view model that will correspond to 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 becomes strongly typed to the view model of course:

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

    Now let's suppose that for some foolish reason you don't want to use view models. In this case you could turn your view into spaghetti code if you prefer:

    @model IEnumerable
    
    @{
        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)
        )
    )
    

提交回复
热议问题