(二)ASP.NET MVC 起步

來源:互聯網
上載者:User

標籤:action   執行   包含   model   產生   對象   htm   port   瀏覽器   

(1) 項目的建立:(註:我是用VS2015的,後面都是) 建立項目→Visual C#→ 【ASP.NET Web 應用程式】,不要勾選【將 Application Insights 添加到項目】,然後【確定】。在下一步介面中選中“Empty”,勾選 【MVC】,不要勾選 【Host in the cloud】。

 

 

(2) 控制器和視圖的建立:在 Controllers 檔案夾下點右鍵→ 【添加】→ 【控制器】→ 選擇【MVC 5 控制器 -空】,類的名字以 Controller 結尾,比如 “TestController”, 會自動在 View 檔案夾下建立一個 Test 的檔案夾(如果不沒有,就手動在 View 下建立 一個,這個檔案夾的名字必須是 TestController 去掉 Controller),在 View/Test 下建立視圖 Index (和TestController 的 Index 方法一致):添加→ 視圖。

 

 (3) 建立一個用來收集使用者參數的類:在Models 檔案夾下建立一個 TestModel(類名無所謂)包含 Num1,Num2 和 Result 三個屬性,然後聲明一個TestModel 用來給view傳遞資料顯示。

 1 public class TestController : Controller 2 { 3     public ActionResult Index(TestModel model) 4     { 5         TestModel res = new TestModel(); 6         res.Num1 = model.Num1; 7         res.Num2 = model.Num2; 8         res.Result = res.Num1 + res.Num2; 9         return View(res);10     }11 }

(4) 在 Index.cshtml 如下編寫:

 1 @model WebApplication2.Models.TestModel 2  3 <!DOCTYPE html> 4  5 <html> 6 <head> 7     <meta name="viewport" content="width=device-width" /> 8     <title>Test</title> 9 </head>10 <body>11     <div> 12         <input type="text" value="@Model.Num1"/>+<input type="text" value="@Model.Num2" />[email protected]13     </div>14 </body>15 </html>

(5) 啟動調試:在Index.cshtml 中右鍵→ 【在瀏覽器中查看】,在地址後面加上參數,比如 http://localhost:55316/Test/Index?Num1=4&Num2=5, 當使用者訪問的時候,會找到 Controllers 檔案夾下的 TestController 的 Index 方法去執行,把請求的參數按照名字填充到 Index 方法的參數對象中(MVC 引擎負責建立對象,給資料賦值,並且進行類型的轉換),return View(res) 就會找到 Views 下的和自己的“類名,方法名”相對應的 Index.cshtml,然後反資料 res 給到 Index.cshtml 去顯示。 

@model WebApplication2.Models.TestModel 表示傳遞過來的資料是TestModel類型的。cshtml 模板就是簡化 HTML 拼接的模板,最終還是產生 HTML 給瀏覽器顯示,不能直接存取 cshtml 檔案。

(二)ASP.NET MVC 起步

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.