標籤:style blog http io ar color os sp 檔案
文章來源: Slark.NET-部落格園 http://www.cnblogs.com/slark/p/mvc-5-get-started-route.html
上一節:ASP.NET MVC 5 入門教程 (2) 控制器Controller
源碼下載:點我下載
上一節我們講了如何建立一個控制器,本節我們來討論如何通過路由來存取控制器及其Action。
那麼問題來了,怎麼寫url能訪問到我想要訪問的控制器呢?
要想正確訪問路由器,就得知道路由規則。它被寫在解決方案的App_Start檔案夾下的RoutConfig.cs檔案中。顧名思義,這是路由設定檔。代碼如下。
using System.Web.Mvc;using System.Web.Routing;namespace SlarkInc{ public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } }}
代碼中標記出的兩行就是路由規則的關鍵所在。
第一行的意思是通過 “http://主機名稱:連接埠號碼/控制器名/Action名/參數id” 可以調用這個控制器的Action並且這個Action帶有參數id。
我們先來建立一個這樣的控制器。
開啟解決方案下的Controllers檔案夾下的FirstController.cs檔案。寫入如下代碼。
using System.Web.Mvc;namespace SlarkInc.Controllers{ public class FirstController : Controller { public string Index(string id) { return "This is first controller index page.<br/> Your Id is " + id; } public string Another() { return "This is first controller another page"; } }}
代碼中標記的部分就是我們想要訪問的Action。
按F5啟動程式。
我們要訪問的是First控制器下的Index Action並且參數是id。
代入公式:“http://主機名稱:連接埠號碼/控制器名/Action名/參數id”
得 http://localhost:57231/first/index/2
結果如下:
Ok。
下面來看RoutConfig.cs檔案標記出的第二行。如下:
url: "{controller}/{action}/{id}",defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
第二行的意思是如果不寫controller那麼controller就預設是Home。確定controller之後如果不寫action則action就預設是Index。id = UrlParameter.Optional表示id可以有也可以沒有。比如調用First控制器的Index Action時就有參數,此時寫上id。如果調用First控制器的Another Action,沒有參數就不寫。
那麼url就是這樣: http://localhost:57231/first/another
運行結果如下:
現在我想讓程式一啟動就顯示FirstController的Index Action,這樣測試起來方便。怎麼辦?
把FirstController 和Index Action都設成預設就行啦。
url: "{controller}/{action}/{id}",defaults: new { controller = "First", action = "Index", id = UrlParameter.Optional }
運行結果如下。id沒給,所以是null,這裡就沒有Id:
下一步我們就可以著手建立View啦。敬請期待。
ASP.NET MVC 5 入門教程 (3) 路由route