ASP.NET MVC 5 入門教程 (3) 路由route

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.