標籤:
首先簡單總結一下這次做網站的經驗。
順序是這樣的:先進行需求分析→然後開始搭建Model→再開始搭建控制器架構→再建立view→建立資料庫→完善網站
最主要的是model要規劃好,然後就是在控制器架構,是寫完整還是寫大概,這是一個問題,這次人家的思維嚴密,所以沒有錯,但是我就不一定了。
然後就是是這次感覺作者對C#瞭解很深,熟練的運用了它的集合List,然後一些處理方法,讓網站很簡單。
先介紹一下對控制器傳到頁面的model強型別的處理。
建立model的時候
[DisplayName("會員資訊")][DisplayColumn("Name")]public class Member{View Code
在類上面打上標籤,然後就在頁面中可以通過以下的方式讀取
對傳過來的list資料
@model IEnumerable<Shopping.Models.Product>
@Html.DisplayNameFor(model => model.ToList()[0])
對傳過來的單個資料()
@model Shopping.Models.Product
@Html.DisplayNameFor(m => m)
而且對資料可以直接取用 new { ProductId = Model.Id}
Ajax和分頁
在MVC中,對這兩個用起來很簡單
不過有點需要注意的是,對
<script src="~/scripts/jquery.unobtrusive-ajax.js"></script>的引用只能放在模板頁才會有效果,很神奇
分頁的頁面中需要因引入就很多
@using PagedList
@using PagedList.Mvc
和樣式
<link href="~/Content/PagedList.css" rel="stylesheet" />
在控制器中需要引入
using PagedList;
然後下面是在控制器中的代碼
//商品列表 public ActionResult ProductList(int id=1, int p = 1) { var productCategory = db.ProductCategories.Find(id); if(productCategory != null) { var data = productCategory.Products.ToList(); var pageDate = data.ToPagedList(pageNumber: p, pageSize: 10); return View(pageDate); } else { return HttpNotFound(); } }View Code
HTML中的代碼
@using PagedList@using PagedList.Mvc@model IEnumerable<Shopping.Models.Product>@{ ViewBag.Title = "ProductList";}<link href="~/Content/PagedList.css" rel="stylesheet" /><h2>@Html.DisplayNameFor(model => model.ToList()[0])</h2><h3>您正在瀏覽【@Model.First().ProductCategory.Name】分類的商品:</h3>@{ var ajaxOption = new AjaxOptions() { OnSuccess = "AddToCartSuccess", OnFailure = "AddToCartFailure", HttpMethod = "Post" };}<script type="text/javascript"> function AddToCartSuccess() { alert(‘添加購物車成功‘); } function AddToCartFailure(xhr) { alert(‘添加購物車失敗(Http狀態代碼:‘ + xhr.status + ‘)‘); }</script><table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.Name) </th> <th> @Html.DisplayNameFor(model => model.Description) </th> <th> @Html.DisplayNameFor(model => model.Price) </th> </tr>@foreach (var item in Model) { <tr> <td> @Html.ActionLink(item.Name, "ProductDetail", new { id = item.Id}) </td> <td> @Html.DisplayFor(modelItem => item.Description) </td> <td> @Html.DisplayFor(modelItem => item.Price) </td> <td> @Ajax.ActionLink("添加購物車", "AddToCart", "Cart", new { ProductId = item.Id}, ajaxOption) </td> </tr>}</table>@{ var data = Model as IPagedList<Shopping.Models.Product>;}@Html.PagedListPager(list: data, generatePageUrl: page => Url.Action("ProductList", new { p = page}))View Code
通過p相互聯絡起來
分頁和Ajax就做好了
對於資料內容
using System.Data.Entity;
public class ShoppingContext:DbContext
{
public ShoppingContext() : base("name=connstr")
{
}
public DbSet<ProductCategory> ProductCategories { get; set; }
}
但是首先還是要用引入資料庫的方式將EntityFramework之類的引用放進來
然後就可以很海參的使用EF了
好了,就總結到這裡了。
照著書抄的購物網站