WebGrid grid.Columns格式错误

时间:2012-01-25 10:12:57

标签: asp.net-mvc-3 razor webgrid

@{
    var grid = new WebGrid(Model.Auctions, rowsPerPage: Model.PagingInfo.ItemsPerPage, defaultSort: "AddedDate");
}

@grid.GetHtml(
        columns: grid.Columns(
                **grid.Column(columnName: "", header: "Type", format: (auction) => AuctionListViewModel.GetAuctionType(auction)),**
                grid.Column(columnName: "OwnerReference", header: "Owner reference")
            )
        );

public class AuctionListViewModel
    {
        public IEnumerable<Auction> Auctions { get; set; }
        public IEnumerable<Item> Items { get; set; }
        public PagingInfo PagingInfo { get; set; }
        public string Title { get; set; }
        public string Action { get; set; }

        public static string GetAuctionType(Auction auction)
        {
            var type = string.Empty;
            if (auction is LubAuction)
            {
                type = "Lowest unique wins";
            }
            else if (auction is EsfAuction)
            {
                type = "Highest wins";
            }

            return type;
        }
    }

使用上面的视图代码和模型,在以粗体标记的行上得到以下错误,为什么会这样?

'UI.Models.AuctionListViewModel.GetAuctionType(UI.AuctionService.Auction)'的最佳重载方法匹配有一些无效的参数

2 个答案:

答案 0 :(得分:2)

grid.Column方法的format参数的参数(在您的情况下为auction)中,您获得了实际项目(Auction),但它被包装到名为{的动态包装器中{3}}。

您可以在此包装器上使用您的属性,并将其委托给实际项目,例如:auction.Title将起作用,但如果您想获取整个项目(Auction),则需要使用WebGridRow的值属性。

format: auction => 
      uctionListViewModel.GetAuctionType(((WebGridRow)auction).Value)

答案 1 :(得分:1)

由于WebGrid帮助器的动态(弱)类型,您需要一个强制转换:

grid.Column(
    columnName: "", 
    header: "Type", 
    format: (auction) => AuctionListViewModel.GetAuctionType((Auction)auction.Value)
)

我建议您使用更好的网格帮助程序,例如MvcContrib GridTelerik Grid,这样可以为您提供强大的输入和编译时安全性。