標籤:style blog http io color os sp for on
實現自己的Controller
平常定義的Controller都繼承自Controller類,Controller類又繼承ControllerBase,其最後又實現了IController介面
public interface IController { void Execute(RequestContext requestContext); }
實現自己的Controller
在Controller檔案夾中建立一個類,取名為MineController,讓後實現IController介面
public void Execute(System.Web.Routing.RequestContext requestContext) { DateTime time = requestContext.HttpContext.Timestamp; string action = requestContext.RouteData.Values["action"].ToString() ; requestContext.HttpContext.Response.Write(string.Format("時間{0},action name{1}", time.ToString(), action)); }
在瀏覽器中輸入http://localhost:8398/Mine/Index
成功實現了自己手寫的一個Controller控制器
當然在實現控制器的時候,我們還是繼承 Controller 抽象類別
資料的互動
Controller擷取資料的三種途徑主要為1.一系列的內容物件2.傳遞給Action方法的參數3.顯示的調用架構的模型繫結(Model Binding)特性
內容物件:Request、Response、RouteData、HttpContext 和 Server
Controller抽象類別中封裝了主要的內容物件
public HttpContextBase HttpContext { get; } public HttpRequestBase Request { get; } public HttpResponseBase Response { get; } public HttpServerUtilityBase Server { get; } public HttpSessionStateBase Session { get; }
當然我們可以像在webform中那樣Request.Form,request.Querystring的形式去擷取值
傳遞給Action的參數
在第一種方法中我們通過擷取上下文資訊的方式來擷取資料,在mvc中封裝了更強大的擷取資訊的方式,我們只要在Action的方法中傳入參數就可以擷取其值
DateTime time = requestContext.HttpContext.Timestamp; string action = requestContext.RouteData.Values["action"].ToString() ;
通過mvc的封裝,我們可以改寫成
public ActionResult Index(DataTime time,string action){}
而且這種簡潔的方式還不用區分其大小寫
為什麼可以通過這種方式進行傳值:
Controller 類通過 MVC 架構的 value provider 和 model binder 組件來為 Action 方法擷取參數的值。
value provider 提供了一系列Controller中可以訪問到的值,在內部它通過從 Request.Form、Request.QueryString、Request.Files 和 RouteData.Values 等內容物件中提取資料(索引值集合),然後把資料傳遞給 model binder,model binder 試圖將這些資料與Action方法的參數進行匹配。預設的 model binder 可以建立和賦值給任何.NET類型對象參數(即 Action 方法的參數),包括集合和自訂的類型。
實現自己的ActionResult
在Controller中定義了很多的ActionResult,下面我們就自己實現自己的ActionResult,我們先看看抽象類別ActionResult中有什嗎?
public abstract class ActionResult { protected ActionResult(); public abstract void ExecuteResult(ControllerContext context); }
看來要實現ActionRsult,繼承後主要是要重寫ExecuteResult的方法,我們建立一個類MyActionResult
public class MyActionResult:ActionResult { public override void ExecuteResult(ControllerContext context) { string controller = context.RouteData.Values["controller"].ToString(); context.HttpContext.Response.Write(string.Format("控制器名稱{0}", controller)); } }
控制器中我們建立一個Actionresult
public ActionResult testMyController() { return new MyActionResult(); }
在瀏覽器中輸入http://localhost:8398/Login/testMyController
可以看到我們自訂的ActionResult已經成功實現了
Action傳遞資料到view視圖中
前面已經介紹了從view視圖傳遞資料到action的的幾種方式,現在來總結一下action傳遞資料到view中去的幾種方法
ViewModel對象
public ActionResult testMyController() { DateTime time = DateTime.Now; return View(time); }
@model DateTime@{ ViewBag.Title = "testMyController";}<h2>testMyController</h2><span>the day is @Model.DayOfWeek</span>
在前台@model 的作用是聲明 model 屬性的類型,省去了類型轉換的麻煩,而 @Model 是View Model 對象的引用。
還有幾種方式ViewBag、ViewData 和 TempData 屬性
ASP.NET MVC之Controller學習2