在上一篇的EF之DB First中,存在以下的兩個(gè)問題:
1. 添加/編輯頁面顯示的是屬性名稱,而非自定義的名稱(如:姓名、專業(yè)...)
2. 添加/編輯時(shí)沒有加入驗(yàn)證
3. 數(shù)據(jù)展示使用分頁
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" }) 是顯示屬性Name的“標(biāo)簽”,如果沒有指定Display特性,則直接顯示屬性名Name
通用數(shù)據(jù)庫生成的實(shí)體模型文件與代碼一般不直接修改(防止下次生成時(shí)覆蓋),這里要使用驗(yàn)證與實(shí)體分離
添加一個(gè)驗(yàn)證類,代碼如下 :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
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= "學(xué)號(hào)" )] [Required] [StringLength(20,MinimumLength =10,ErrorMessage = "長度為10-20" )] public string StudentId { get ; set ; } } } |
此時(shí)前臺(tái)訪問并提交:
從上圖可以發(fā)現(xiàn)Name變成了“姓名”,StudentsId變成了“學(xué)號(hào)”,點(diǎn)擊Create按鈕后,出現(xiàn)了驗(yàn)證提示信息。
分頁的實(shí)時(shí)使用PagedList.MVC插件,可以nuget添加引用
StudentsController中增加一個(gè)List的控制器方法:
1
2
3
4
5
6
|
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)); } |
視圖代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
@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 > 學(xué)號(hào) </ th > < th > 專業(yè) </ 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})) |
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。