在ASP.Net MVC架構中是使用地址攔截的,雖然很好用,但是裝起來太大了,配置也麻煩。本文通過代碼實踐,在ASP.Net2.0架構下實現一套簡易的MVC架構。MVC架構難於構建的地方在於Controller與View的分離以及分離後資料可以方便地傳輸。為了保持代碼的簡潔,將使用ashx檔案作為Controller,用aspx頁面作為View。
講起來比較費勁,把專案檔放上來,而下面只作一個簡單的說明。項目是VS2008的項目,大小15K。
:DotNetMVC.rar
首先構建一個Controller基類。
Controller類
/**
* author : yurow
* http://birdshover.cnblogs.com
* description:
*
* history : created by yurow 2009-9-20 7:30:04
*/
using System.Web;
using System.Web.Services;
namespace DotNetMVC.MVC {
/// <summary>
/// 控制器
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public abstract class Controller<T, K> : IHttpHandler {
/// <summary>
/// 當前請求
/// </summary>
protected MyRequest Request;
/// <summary>
/// 輸出
/// </summary>
protected HttpResponse Response;
/// <summary>
/// 返回到View頁面的資料
/// </summary>
protected MvcViewData<T, K> ViewData;
/// <summary>
/// 控制器名稱
/// </summary>
private string controllerName;
/// <summary>
/// 控制器操作方法
/// </summary>
public abstract void Action();
/// <summary>
/// 執行請求
/// </summary>
/// <param name="context"></param>
public void ProcessRequest(HttpContext context) {
Request = context.Request;
Response = context.Response;
//這裡可以用反射的方式進行帶參數的操作,這裡為了簡化,去掉了這部分
//MethodInfo method = this.GetType().GetMethod("Action", new Type[0]);
//if (method == null) {
// throw new NotImplementedException("沒有實現!");
//}
//object data = method.Invoke(this, null) as object;
ViewData = new MvcViewData<T, K>();
Action();
context.Items.Add("MvcViewData", ViewData);
context.Server.Transfer("~/View/" + ControllerName + ".aspx", false);
}
/// <summary>
/// 控制名稱,不設定預設為View頁面與控制器名稱同名
/// 比如,在Login.ashx請求中,預設調用View/Login.aspx的頁面作為顯示頁面。
/// 當登入成功後,設定其為LoginOK,則會調用View/LoginOK.aspx
/// </summary>
protected string ControllerName {
get {
if (string.IsNullOrEmpty(controllerName))
return this.GetType().Name;
return controllerName;
}
set {
controllerName = value;
}
}
public bool IsReusable {
get {
return false;
}
}
}
}
Controller在ProcessRequest方法中調用aspx頁面,裡面設定了一個虛方法Action在具體的ashx檔案中重載。
下面是Default.ashx.cs檔案的寫法
Default
sing DotNetMVC.MVC;
namespace DotNetMVC {
/// <summary>
/// $codebehindclassname$ 的摘要說明
/// </summary>
public class Default : Controller<string, string> {
public override void Action() {
}
}
}
在Controller中,還有兩個重要的東西一個是傳遞給View資料用的,一個是顯示哪個View的(通過ControllerName這個屬性)