asp.net mvc(一)
這些天開始學習asp.net mvc,用傳統的asp.net已經快四的年了,剛開始接觸asp.net mvc確認感覺有點不適應,主要體現在asp.net mvc的實現上。
問題一:要想學習asp.net mvc,我個人覺的最重要的一步是知道mvc路由機制,傳統的asp.net程序要想訪問一個頁面,都是根據頁面路徑來訪問,但MVC並不能直接訪問aspx頁面。
問題二:理解MVC三部分的含義和用法。當我們創建一個asp.net mvc應用程序時,系統會默認生成三個文件夾:
1:Controllers,對應MVC中的C,主要是處理所有請求與做出對應的響應;
2:Models,對應MVC中的M,相當時我們平時創建工程中的實體工程,只不過在MVC中它充當了存放數據模型的作用;
3:Views,對應MVC中的V,這里就是存放用戶訪問的頁面文件,但是這個文件不能在瀏覽器中根據路徑訪問。
對於系統生成的asp.net mvc項目,我對其做了如下擴展:
擴展點一:系統之所以在web工程中直接創建了三個文件夾,是為了更加直觀的體現MVC模式,真正項目中我們需要把它們分開。
擴展點二:MVC中重要的路由處理,默認情況是在Global.asax文件中,我們也可以把這塊內容獨立出來。
擴展點三:把Controller類和業務邏輯分離,這里可以采用Repository模式。
案例DEMO:創建一個簡單的留言簿的項目,數據存儲采用sql,本想用linq to entity,但總覺的這部分還相關不完善,且性能存在問題,故使用傳統ado.net實現數據存儲。下面是這個項目的分層。
1:GuestBook.Web,頁面表示層 ,MVC中的V。
2:GuestBook.MVC.Controller,存放項目所有的Controller,MVC中的C。我們知道Controller有兩個作用:第一,處理請求;第二,做出對應的響應。第二點就是我們平時理解的后台功能實現,例如數據的增刪改查等。我們可以把這部分功能與Controller分離,即所有的業務邏輯都寫在業務邏輯層,不直接依賴Controller,我們可以進一步把這些功能點抽象出來,讓Controller依賴一個公共的接口。這個思想我之前的一篇文章有點異曲同工之處:對增刪改查用面向對象進行包裝
首先:創建一個Repository接口:IRepository.cs,里面包含些常見數據處理操作方法:這個接口是一個泛型接口,以實現所有實體類的通用性。
public interface IRepository<T> { List<T> FindAllInfo(); T GetInfo(T model); bool Add(T model); bool Delete(T model); bool Edit(T model); }
然后:實現一條留言的數據處理:
public List<GuestBookInfo> FindAllInfo() { string sql = "select * from GuestBook"; List<GuestBookInfo> list = new List<GuestBookInfo>(); using(SqlDataReader dr=SqlHelper .ExecuteReader (conn ,CommandType .Text ,sql )) { while (dr.Read()) { GuestBookInfo model = new GuestBookInfo(); model.ID = int.Parse (dr["ID"].ToString()); model.sTitle = dr["sTitle"].ToString(); model.sContent = dr["sContent"].ToString(); list.Add(model); } } return list ; } public GuestBookInfo GetInfo(GuestBookInfo model) { string sql = "select * from GuestBook where ID="+model.ID .ToString (); using (SqlDataReader dr = SqlHelper.ExecuteReader(conn, CommandType.Text, sql)) { if (dr.Read()) { model.ID = int.Parse(dr["ID"].ToString()); model.sTitle = dr["sTitle"].ToString(); model.sContent = dr["sContent"].ToString(); } } return model ; } public bool Add(GuestBookInfo model) { string sql = "insert into GuestBook (sTitle,sContent) values ('" + model.sTitle + "','" + model.sContent + "')"; int i = SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql); if (i > 0) { return true; } return false ; } public bool Delete(GuestBookInfo model) { string sql = "delete GuestBook where ID=" + model.ID.ToString(); int i = SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql); if (i > 0) { return true; } return false; } public bool Edit(GuestBookInfo model) { string sql = "update GuestBook set sTitle='" + model.sTitle + "',sContent='" + model.sContent + "' where ID=" + model.ID.ToString(); int i = SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql); if (i > 0) { return true; } return false; }
其實:Controller依賴IRepository接口。
public class GuestBookController : System.Web.Mvc.Controller { IRepository<GuestBookInfo> inter = new BLL_GuestBook(); public ActionResult Index() { var models = inter.FindAllInfo(); return View("Index", models); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(GuestBookInfo model) { inter.Add(model ); return RedirectToAction("Index"); } public ActionResult Create() { GuestBookInfo model = new GuestBookInfo(); return View(model ); } public ActionResult Details(int id) { GuestBookInfo model=new GuestBookInfo (); model .ID =id; model =inter.GetInfo (model ); if (string .IsNullOrEmpty (model.sTitle )) { return View("NotFound"); } else { return View("Details",model ); } } public ActionResult Edit(int id) { GuestBookInfo model = new GuestBookInfo(); model.ID = id; model = inter.GetInfo(model); if (string.IsNullOrEmpty(model.sTitle)) { return View("NotFound"); } else { return View("Edit", model); } } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(int id, FormCollection formValues) { GuestBookInfo model = new GuestBookInfo(); model.ID = id; model = inter.GetInfo(model); UpdateModel(model ); inter.Edit(model); return RedirectToAction("Index"); } public ActionResult Delete(int id) { GuestBookInfo model = new GuestBookInfo(); model.ID = id; model = inter.GetInfo(model); if (model == null) return View("NotFound"); inter.Delete(model); return RedirectToAction("Index"); } }
3:GuestBook.Model,MVC中的M。
4:GuestBook.RouteManager,路由管理項目,把路由處理從Global.asax中分離開。我們創建一個新類:MyMvcAppliation.cs
public class MyMvcAppliation:HttpApplication { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" }, // Parameter defaults new string[] { "GuestBook.MVC.Controller" } ); } protected void Application_Start() { ControllerBuilder.Current.DefaultNamespaces.Add("GuestBook.MVC.Controller"); RegisterRoutes(RouteTable.Routes); } }
5:GuestBook.Data,數據處理工具類,例如SqlHelp等等。
6:GuestBook.DAL,數據處理層。
7:GuestBook.BLL,業務邏輯層。
8:GuestBook.MyInterface,相關接口,本項目中包含Repository模式中的接口類。