如何显示在MVC中的WebGrid行数 [英] How to display row number in MVC WebGrid

查看:314
本文介绍了如何显示在MVC中的WebGrid行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有一个列在MVC中的WebGrid 行号。我该怎么办呢?

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

推荐答案

您可以使用将包含一个属性,来指示行号视图模型。

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; }
}

和则:

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<MyViewModel>

@{
    var grid = new WebGrid(Model);
}

@grid.GetHtml(
    columns: grid.Columns(
        grid.Column("RowNumber"),
        grid.Column("Foo")
    )
)

现在让我们假设,由于某种原因,愚蠢的,你不希望使用视图模型。在这种情况下,你可以把你的看法变成面条code,如果你preFER:

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<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)
    )
)

这篇关于如何显示在MVC中的WebGrid行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆