设为首页 加入收藏

TOP

asp.net MVC 使用PagedList.MVC实现分页
2017-10-13 10:40:17 】 浏览:4633
Tags:asp.net MVC 使用 PagedList.MVC 实现

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

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

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

另外数据展示使用分页

@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; }
    }
}
View Code

 

此时前台访问并提交:

 

从上图可以发现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));
        }
View Code

 

视图代码如下:

@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}))
View Code

 

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇背水一战 Windows 10 (60) - 控件.. 下一篇[Open Source] .NET 基于StackExc..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目