Inherits="ViewPage<PageData<User>>",享受 IntelliSense 與編譯期檢查PageData<T> 封裝資料、總筆數、頁大小、當前頁ActionResult Add(User model) 直接接收 POST 資料
public class PageData<T>
{
public List<T> Data { get; set; } = new List<T>();
public int TotalCount { get; set; }
public int PageSize { get; set; } = 5;
public int PageIndex { get; set; }
}
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<Web.Models.PageData<Web.Models.User>>" %>
<table>
<thead><tr><th>ID</th><th>帳號</th><th>操作</th></tr></thead>
<tbody>
<% foreach (var u in Model.Data) { %>
<tr>
<td><%: u.Id %></td>
<td><%: u.UserName %></td>
<td>
<a href="/Demo/Edit/<%: u.Id %>">編輯</a> |
<a href="/Demo/Delete/<%: u.Id %>" onclick="return confirm('確定刪除?')">刪除</a>
</td>
</tr>
<% } %>
</tbody>
</table>
<div id="Pagination"></div>
<a href="/Demo/Create">新增</a>
<script>
$(function() {
$("#Pagination").pagination(<%= Model.TotalCount %>, {
callback: function(page) { location.href = "?page=" + page; },
items_per_page: <%= Model.PageSize %>,
current_page: <%= Model.PageIndex %>,
prev_text: "« 上一頁",
next_text: "下一頁 »",
num_display_entries: 5,
num_edge_entries: 1
});
});
</script>
public ActionResult List(int? page)
{
int pageIndex = page ?? 1;
var paged = UserService.GetPagedList(pageIndex, 5); // 回傳 PageData
return View(paged);
}
[HttpGet]
public ActionResult Create() => View();
[HttpPost]
public ActionResult Create(User model)
{
if (ModelState.IsValid)
{
UserService.Add(model);
return RedirectToAction("List");
}
return View(model);
}
[HttpGet]
public ActionResult Edit(int id)
{
var user = UserService.GetById(id);
return View(user);
}
[HttpPost]
public ActionResult Edit(User model)
{
if (ModelState.IsValid)
{
UserService.Update(model);
return RedirectToAction("List");
}
return View(model);
}
public ActionResult Delete(int id)
{
UserService.Delete(id);
return RedirectToAction("List");
}
<%@ Page Inherits="ViewPage<Web.Models.User>" %>
<form action="/Demo/Create" method="post"> <!-- Edit 為 /Demo/Edit -->
<table>
<tr><td>帳號:</td><td><input name="UserName" value="<%: Model.UserName %>" /></td></tr>
<tr><td>密碼:</td><td><input type="password" name="Password" /></td></tr>
<tr><td colspan="2"><input type="submit" value="送出" /></td></tr>
</table>
</form>
關鍵:name 屬性必須與 User 類別屬性名稱完全一致(UserName, Password),MVC 模型繫結器才能自動填入。
public class User
{
public int Id { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
