標籤:控制器 web mvc controller
用NFinal架構開發的項目類似於MVC的那種開發方式,有Controller層、Model層、View層,還包括表現層Web層,在NFinal開發的項目中真正執行的代碼也就是Web層中的代碼,Web中的代碼是根據Controller與View模板中的代碼產生的執行代碼,我們只需要在Controller中寫好邏輯,在View中設計好頁面然後運行WebComplier.aspx即可產生整個Web檔案夾,然後只需要運行Web中相應的HTML頁面即可。那麼首先來看下控制器相關的東西。
控制器的定義
1.控制器必須寫在Controllers目錄下.
2.命名空間採用預設的命名空間,類名必須以Controller結尾,且必須繼承自Controller基類.
3.其函數傳回值類型為void,修飾符為public.
例:
1、在Controllers下建立SampleController.cs
using System.Collections.Generic; using System.Web; //由於項目名和模組名不同,命名空間也會不同,複製該代碼也是無法啟動並執行. //必須手動添加該類,或是修改為正確的命名空間. namespace WebMvc.App.Controllers { public class SampleController:Controller { public void Show() { Write("Hello World."); } } }
2、右鍵點擊WebCompiler.aspx選擇在瀏覽器中查看
產生開始
產生結束
3、重新整理專案檔夾會發現在Web層的Default檔案夾下會出現SampleController檔案夾.右鍵點擊該檔案夾選擇包括在項目中,可以看到檔案夾下有Show.cs與Show.html兩個檔案.
其中Show.cs的代碼如下:
using System; using System.Collections.Generic; using System.Web; namespace WebMvc.App.Web.Default.SampleController { public class ShowAction : Controller { public ShowAction(System.IO.TextWriter tw):base(tw){} public ShowAction(string fileName) : base(fileName) {} public void Show() { Write("Hello World."); } } }
Show.html中的代碼如下:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title</title> </head> <body> <script> window.location.href = "/App/SampleController/Show.htm"; </script> </body> </html>
Show中的代碼只是跳轉並執行SampleController下的Show()方法.
4、右鍵點擊並選擇在瀏覽器中查看.可以看到瀏覽器輸出Hello World.
NFinal 揭秘之控制器