MVC3的webgrid分页
{
public int GenreId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public List<Album> Albums { get; set; }
}
{
public int ArtistId { get; set; }
public string Name { get; set; }
}
public class Album
{
[ScaffoldColumn(false)]
public int AlbumId { get; set; }
[DisplayName("Genre")]
public int GenreId { get; set; }
[DisplayName("Artist")]
public int ArtistId { get; set; }
[Required(ErrorMessage="An Album Title is requested")]
[StringLength(160)]
public string Title { get; set; }
[Required(ErrorMessage="Price is requested")]
[Range(0.00,100.00,ErrorMessage="价格必须在0.00到100.00之间")]
public decimal Price { get; set; }
[DisplayName("Album Art Url")]
[StringLength(1024)]
public string AlbumArtUrl { get; set; }
public virtual Genre Genre { get; set; }
public virtual Artist Artist { get; set; }
}
Controller里获取数据:
return View(albums.ToList());
注意,Genre和Artist是内联对象
View如下:
@model IEnumerable<MvcSample.Models.Album>
@{
ViewBag.Title = "Index";
}
<h2>
Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
@{
var grid = new WebGrid(source: Model, fieldNamePrefix: "", defaultSort: "Genre", canPage: true, canSort: true, ajaxUpdateContainerId: "DivGrid", pageFieldName: "paging", sortFieldName: "Artist", rowsPerPage: 20);
}
<div id="DivGrid">
@grid.GetHtml(
columns:
grid.Columns(
grid.Column("Genre", "Genre", format: item=>item.Genre.Name,canSort:true),
grid.Column("Artist", "Artist", format: item=>item.Artist.Name,canSort:true),
grid.Column("Title", "Title", format: @<text>@item.Title</text>),
grid.Column("Price", "Price", format: @<text>@item.Price</text>),
grid.Column("", "", format:@<text> @Html.ActionLink("Edit", "Edit", new { id = item.AlbumId }) |
@Html.ActionLink("Details", "Details", new { id = item.AlbumId }) |
@Html.ActionLink("Delete", "Delete", new { id = item.AlbumId })</text>)
)
)
<p>总页数:@grid.PageCount | 每页:@grid.RowsPerPage 行 | 当前第 @(grid.PageIndex + 1) 页</p>
</div>
此时点击列Genre和Artist,是没有排序效果的,其实是有刷新,但都是获取默认数据视图。我们可以看一下生成的HTML代码
<th scope="col"><a href="#" onclick="$('#DivGrid').load('/storemanager?Artist=Genre&sortdir=ASC&__=634697837603269528 #DivGrid');">Genre</a></th>
可以看到红色的是排序的列参数,但在Album里,是没有这一属性的,必须把Genre改成Genre.Name才可以。
所以在View里,必须修改这两行
grid.Column("Artist.Name", "Artist", format: item=>item.Artist.Name,canSort:true),