首页 > 编程 > .NET > 正文

asp.net MVC使用PagedList.MVC实现分页效果

2020-01-17 22:19:09
字体:
来源:转载
供稿:网友

在上一篇的EF之DB First中,存在以下的两个问题:

1. 添加/编辑页面显示的是属性名称,而非自定义的名称(如:姓名、专业...)

2. 添加/编辑时没有加入验证

3. 数据展示使用分页

@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" }) 是显示属性Name的“标签”,如果没有指定Display特性,则直接显示属性名Name

通用数据库生成的实体模型文件与代码一般不直接修改(防止下次生成时覆盖),这里要使用验证与实体分离

添加一个验证类,代码如下 :

using System.ComponentModel.DataAnnotations;namespace Zhong.Web.Models{ [MetadataType(typeof(T_StudentValidateInfo))] public partial class T_Student { } public class T_StudentValidateInfo {  [Display(Name="姓名")]  [Required(ErrorMessage ="姓名不能为空")]  [StringLength(10,ErrorMessage ="姓名长度超出限制")]  public string Name { get; set; }  [Display(Name="学号")]  [Required]  [StringLength(20,MinimumLength =10,ErrorMessage ="长度为10-20")]  public string StudentId { get; set; } }}

此时前台访问并提交:

从上图可以发现Name变成了“姓名”,StudentsId变成了“学号”,点击Create按钮后,出现了验证提示信息。

分页的实时使用PagedList.MVC插件,可以nuget添加引用

StudentsController中增加一个List的控制器方法:

public ActionResult List(int page = 1){ //var students = entities.T_Student.OrderBy(s => s.Id).Skip((page - 1) * 2).Take(2); var students = entities.T_Student.OrderBy(s => s.Id); return View(students.ToPagedList(page, 2));}

视图代码如下:

@using PagedList.Mvc@model PagedList.IPagedList<Zhong.Web.Models.T_Student>@{ ViewBag.Title = "List";}<h2>List</h2><p> @Html.ActionLink("Create New", "Create")</p><table class="table"> <tr>  <th>   姓名  </th>  <th>   学号  </th>  <th>   专业  </th>  <th></th> </tr>@foreach (var item in Model) { <tr>  <td>   @Html.DisplayFor(modelItem => item.Name)  </td>  <td>   @Html.DisplayFor(modelItem => item.StudentId)  </td>  <td>   @Html.DisplayFor(modelItem => item.T_Major.Name)  </td>  <td>   @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |   @Html.ActionLink("Details", "Details", new { id=item.Id }) |   @Html.ActionLink("Delete", "Delete", new { id=item.Id })  </td> </tr>}</table>@Html.PagedListPager(Model,page => Url.Action("List",new { page}))

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表