1、瀏覽分類
a. 修改Contoller的為如下
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using BookShop.Models; //import model namespace BookShop.Controllers{public class CategoryController : Controller{BookShopDBDataContext db = new BookShopDBDataContext();// Category/Listpublic void List(){List<Category> categories = db.GetAllCategory();RenderView("CategoryList", categories);}// Category/Edit/idpublic void Edit(int id){}//Category/Delete/idpublic void Delete(int id){}//Category/Addpublic void Add(){}}}
b.在view檔案下建立一個對應的Category的檔案夾,在其下建立一個(MVC view content page) CategoryList.aspx
c. 修改CategoryList.aspx.cs為如下代碼:
d. 修改Category.aspx的視圖
e. 瀏覽(因為資料庫裡沒有資料,所以看到如)
2、添加目錄
a. 現在我們來實現建立的功能,修改CategoryController的Add的行為,建立一個AddSaved的行為儲存建立的目錄,並導航到List視圖
//Category/Add
public void Add()
{
RenderView("AddCategory");
}
public void AddSaved()
{
Category newCategory = new Category { CategoryName = Request.Form["CategoryName"] };
db.AddCategory(newCategory);
RedirectToAction(new RouteValueDictionary(new { controller = "Category", action = "List" }));
}
b. 我們需要在view\category\下建一個AddCategory.aspx(MVC view content page)來建立一個視圖
c. 最終效果
3. 修改目錄:
a. 添加下面兩個方法到BookShopDBDataContext部分類別
//Edit Category
public void EditCategory(Category c)
{
this.UpdateCategory(c);
this.SubmitChanges();
}
public Category GetCategory(int id)
{
return Categories.Single(c => c.CategoryId == id);
}
b. 添加下面的方法到CategoryController
// Category/Edit/id
public void Edit(int id)
{
RenderView("EditCategory", db.GetCategory(id));
}
public void EditSaved(int id)
{
Category c=db.GetCategory(id);
c.CategoryName=Request.Form["CategoryName"];
//BindingHelperExtensions.UpdateFrom(c, Request.Form);
db.EditCategory(c);
List<Category> categories = db.GetAllCategory();
RedirectToAction(new RouteValueDictionary(new { controller = "Category", action = "List" }));
}
c. 我們需要在view\category\下建一個EditCategory.aspx(MVC view content page)來建立一個視圖
修改CategoryList.aspx
修改EditCategory.aspx.cs如下
修改EditCategory.aspx如下
d.效果:
4. 刪除目錄
a. 修改CategoryList.aspx
b. 修改CategoryController,添加
c.效果
未完待續。。。