天天看點

ASP.NET MVC5入門指南

1.建立項目

檔案 --> 建立 --> 項目

ASP.NET MVC5入門指南
Visual C# --> Web --> ASP.NET Web應用程式
ASP.NET MVC5入門指南
      MVC此時處于選中狀态,勾選“添加單元測試”(可選擇)。
ASP.NET MVC5入門指南
      完成以上步驟,基本的項目建立完成,此時點選“F5”可運作項目,如下圖所示。(為友善辨別,此後用url代替“localhost:20391”)
ASP.NET MVC5入門指南

MVC代表:模型-視圖-控制器。

Models:辨別該應用程式的資料并使用驗證邏輯來強制實施業務規則的資料類

Views  :應用程式動态生成HTML所使用的模版檔案

Controllers:處理浏覽器的請求,取得資料模型,然後指定要響應浏覽器請求的視圖模版

2. 添加一個控制器類

(右擊)Controllers檔案夾 --> 添加 --> 控制器

ASP.NET MVC5入門指南
選擇“MVC 5 控制器-空”
ASP.NET MVC5入門指南
為控制器添加名稱
ASP.NET MVC5入門指南

      添加後在Controllers檔案夾中會多出檔案“MvcMusicStoreController.cs”,并且在檔案夾Views下會多出“MvcMusicStore”檔案夾

目錄結構如下所示:

ASP.NET MVC5入門指南
      修改控制器“MvcMusicStoreController.cs”檔案中的代碼為:
ASP.NET MVC5入門指南

1     public class MvcMusicStoreController : Controller
 2     {
 3         public string Index()
 4         {
 5             return "This is my <b>default</b> action";
 6         }
 7 
 8         public string Welcome()
 9         {
10             return "This is Welcome action method...";
11         }
12     }      
ASP.NET MVC5入門指南

      此時重新運作程式,位址欄輸入“url/MvcMusicStore”

ASP.NET MVC5入門指南

3.資料路由

      ASP.NET MVC會調用不同的控制器類(和其内部不同的操作方法)這取決于傳入URL。所使用的ASP.NET MVC的預設URL路由邏輯使用這樣的格式來判定哪些代碼以便調用:

      可在App_Start/RouteConfig.cs檔案内通過配置URL路由解析規則:

ASP.NET MVC5入門指南
1     public class RouteConfig
 2     {
 3         public static void RegisterRoutes(RouteCollection routes)
 4         {
 5             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 6 
 7             routes.MapRoute(
 8                 name: "Default",
 9                 url: "{controller}/{action}/{id}",
10                 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
11             );
12         }
13     }      
ASP.NET MVC5入門指南

如果運作程式且不提供任何URL段,預設為“Home”的控制器和Index的操作方法,在上面的代碼中的defaults部分指定:

  •  第一部分的URL确定哪個控制器類會被執行。是以 /MvcMusicStore 映射到MvcMusicStoreController控制器類
  •  第二部分的URL确定要執行控制器類中的那個操作方法。是以 /HelloWorld/Index,會使得 MvcMusicStoreController控制器類的Index方法被執行。請注意,隻需要浏覽 /MvcMusicStore路徑,預設情況下會調用Index方法。如果沒有明确的指定操作方法,Index方法會預設的被控制器類調用。
  • 第三部分的URL段(Parameters參數)是路由資料

      浏覽 url/MvcMusicStore/Welcome 。Welcome方法會被運作并傳回字元串“this is the welcome action method...”。

      預設的MVC映射為 /[Controller]/[ActionName]/[Parameter]對于這個URL,控制器類是MvcMusicStore,操作方法是Welcome,此處并未用到[Parameters]部分。

此處對Welcome方法進行修改,并使用了C#語言的可選參數功能,numTimes參數在不傳值時,預設值為1。

1         public string Welcome(string name,int numTimes =1)
2         {
3             //return "This is Welcome action method...";
4             return HttpUtility.HtmlEncode("Hello " + name + ",NumTimes is :" + numTimes);
5         }      

      此時運作應用程式并浏覽次URL(url/MvcMusicStore/Welcome?name=Long&numtimes=4)

ASP.NET MVC5入門指南

上面的例子,沒有用到URL段參數的部分(Parameters)。通過query strings傳遞name和numTimes的參數

用下面的代碼替換“Welcome”的方法:

1    public string Welcome(string name,int ID =1)
2    {
3        //return "This is Welcome action method...";
4        //return HttpUtility.HtmlEncode("Hello " + name + ",NumTimes is :" + numTimes);
5        return HttpUtility.HtmlEncode("Hello " + name + ",ID:" + ID);
6    }      
ASP.NET MVC5入門指南

這次URL第三部分的參數比對了參數ID。

4.添加一個視圖

      控制器的預設程式是:

1    public ActionResult Index()
2    {
3        return View();
4    }      

      上面的Index方法使用一個視圖模版來生成一個HTML傳回給浏覽器。控制器的方法(也被稱為action method(操作方法)),如上面的Index方法,一般傳回一個ActionResult(或從ActionResult所繼承的類型),而不是原始的類型,如字元串。

      如果想使用控制器中預設的Index方法,則需要在對應的Views中添加視圖檔案。

      在Views/MvcMusicStore -->添加 -->“MVC5 View Page with(Layout Razor)”

ASP.NET MVC5入門指南

      在指定項名稱中,輸入“Index”

ASP.NET MVC5入門指南

      “選擇布局頁(select layout page)”-->"_Layout.cshtml"-->"确定",然後在解決方案資料總管中看到View/MvcMusicStore/Index.cshtml檔案。

ASP.NET MVC5入門指南
ASP.NET MVC5入門指南

      在Index.cshtml檔案中添加以下代碼

ASP.NET MVC5入門指南
1 @{
2     ViewBag.Title = "Index";   
3 }
4 
5 <h2>Index</h2>
6 
7 <p>Hello from our View Template!</p>      
ASP.NET MVC5入門指南

      運作并調試程式,得到界面:

ASP.NET MVC5入門指南

5.修改視圖和布局頁

      首先,想要修改頁面頂部的連結“Application name”。這段文字是每個頁面的公用文字,即使這段文字出現在每個頁面上,但是實際上它僅儲存在工程裡的一個地方。

      在解決方案資料總管裡找到 Views/Shared檔案夾,打開_Layout.cshtml檔案。此檔案稱為布局頁面(Layout page),并且其他所有的子頁面,都共享使用這個布局頁面。

6.将資料從控制器傳遞給視圖

      控制器響應請求來的URL。控制器類是寫代碼來處理傳入請求的地方,并從資料庫中檢索資料,并最終決定什麼類型的傳回結果會發送回浏覽器。視圖模版可以被控制器用來産生格式化過的HTML進而傳回給浏覽器。

      控制器負責給任何資料或者對象提供一個必須的視圖模版,用這個視圖模版來Render傳回給浏覽器的HTML。最佳的做法是:一個視圖模版應該永遠不會執行業務邏輯或者直接和資料庫進行互動。相應的,一個視圖模版應該隻和控制器所提供的資料進行互動。維持這種“隔離關系”。  

1 public ActionResult Index()
2 {
3      return View("NotIndex");  
4 }      

對于這樣的編碼,操作方法依然在/Views/Home目錄中查找視圖,但選擇的不再是Index.cshtml,而是NotIndex.cshtml。

如果需要制定完全位于不同目錄結構中的視圖,編碼如下:

1 public ActionResult Index()
2 {
3      return View("~/Views/Example/Index.cshtml");  
4 }      

7.添加一個模型

      Entity Framework(通常稱為EF)是支援代碼優先(Code First)的開發模式。代碼優先允許通過編寫簡單的類來建立對象模型。

      在解決方案資料總管,(右鍵單擊)模型檔案夾 --> 添加 --> 類

ASP.NET MVC5入門指南

輸入類名“MusicStore”,并為類添加屬性: 

ASP.NET MVC5入門指南
1     public class MusicStore
2     {
3         public int ID { get; set; }
4         public string SongName { get; set; }
5         public string SingerName { get; set; }
6         public DateTime PublishDate { get; set; }
7         public decimal Price { get; set; }
8     }      
ASP.NET MVC5入門指南

類中的每一個屬性對應表中的每一列。在這個類中,添加下面的MusicStoreDBContext類:

1     using System.Data.Entity;
2 
3     public class MusicStoreDBContext : DbContext
4     {
5         public DbSet<MusicStore> Movies { get; set; }
6     }      

      MusicStoreDBContext類代表Entity Framework的音樂資料庫類,這個類負責在資料庫中擷取、存儲、更新、處理MusicStore類的執行個體。MusicStoreDBContext繼承自Entity Framework的DbContext基類。

8.SQL Server Express LocalDB

      LocalDB是一個SQL Server Express輕量級版本的資料庫引擎。它在使用者模式下啟動、執行。LocalDB運作在一個特殊的SQL Server Express的執行模式,即允許能夠使用MDF檔案資料庫。通常情況下,LocalDB的資料庫檔案都儲存在web項目的App_Data檔案夾下面。

      注:在生産環境的Web應用程式中,不推薦使用SQL Server Express。尤其是LocalDB不應該用于Web應用程式的生産環境,因為它沒有被設計要使用IIS,但是LocalDB的資料庫能很容易的遷移到SQL Server或SQL Azure。

      打開應用程式根目錄的Web.config檔案

ASP.NET MVC5入門指南

找到資料庫的連接配接設定代碼:

1   <connectionStrings>
2     <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-MvcMusicStore-20170228045043.mdf;Initial Catalog=aspnet-MvcMusicStore-20170228045043;Integrated Security=True"
3       providerName="System.Data.SqlClient" />
4   </connectionStrings>      

做如下修改:

1   <connectionStrings>
2     <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-MvcMusicStore-20170228045043.mdf;Initial Catalog=aspnet-MvcMusicStore-20170228045043;Integrated Security=True"
3       providerName="System.Data.SqlClient" />
4     <add  name="MusicStoreDBContext" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\MusicStore.mdf;Integrated Security=True" providerName="System.Data.SqlClient"/>
5   </connectionStrings>      

9.從控制器通路資料模型

注:進行該步驟之前,應先編譯程式,這樣才可以使用之前的模型類及上下文類。

Controllers檔案夾 --> 新增 --> Controller --> 選擇控制器

ASP.NET MVC5入門指南

設定模型類、資料上下文類并設定控制器名稱。

ASP.NET MVC5入門指南

完成以上步驟,Visual Studio會建立以下檔案和檔案夾:

  • 控制器檔案夾中的MusicStoreController.cs檔案
  • 項目視圖檔案夾下的MusicStore檔案夾
  • 在新的Views/MusicStore檔案夾中建立Create.cshtml、Delete.cshtml、Details.cshtml、Edit.cshtml和Index.cshtml檔案。

 運作程式,url輸入“url/MusicStore”

ASP.NET MVC5入門指南