練習:html
新建一個mvc項目服務器
要求:mvc
有3個視圖 Login Index Detailspost
目的:
感覺一下MVC與傳統WebForm的差別性url
WebForm的請求模型spa
MVC請求模型.net
傳統WebForm與MVC區別code
WebForm 實際上請求的是一個頁面對象orm
MVC 不只請求了一個頁面對象,還向服務器請求了具體的業務處理方法htm
程序結構以下
一,項目模板和視圖引擎介紹
項目模板
基本: 通常選擇這個 它會自動將一些Jquery庫導入進來
Internet應用程序:外網使用的
Intranect應用程序:內網使用
Web API:一個輕量級的WebService
知識點:
Web API:使用JSON格式傳輸數據
WebService:使用XML格式傳輸數據
視圖引擎:
ASPX:在前臺用<% %>形式寫C#
Razor:在前臺用@語法寫C#
二,添加一個控制器Controller
控制器模板:
空MVC控制器:只有一個默認的Index方法
包含空的讀/寫操做的MVC控制器:會將增刪改查的Action方法自動添加到當前控制器代碼中
三,返回一個String字符串
public string PrintStr() { return "hello mvc4"; }
運行後:
四,添加視圖Login.cshtml
前臺:Login.cshtml
@model MvcApplication1.Models.User @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Login</title> </head> <body> <div> <h3>登陸</h3> ViewBag接收後臺數據:@ViewBag.tips <br /><br /> Model接收後臺數據: @Model.UName <br /><br /> <form action="/User/Login" method="post"> <input type="text" name="UName" /><br /><br /> <input type="password" name="UPwd" /><br /><br /> <input type="submit" value="登入" /> </form> </div> </body> </html>
後臺:
[HttpGet] public ViewResult Login() { //向前臺傳值 ViewBag.tips = "hello, welcome to here"; Models.User model = new Models.User(); model.UName = "華子"; return View(model); }
@{Layout = null;}
表示當前視圖不使用默認的母版頁
後臺向前臺傳值,有兩種方式
ViewBag
Return View(model)
強類型視圖
在csdhmtl頂部指定model類型,形式如@model MvcApplication1.Models.User,就叫強類型型視圖
好處:在VS中能夠智能提示,能夠直接寫如@Model.UName
五,提交Login.cshtml後重定向
前臺:
<form action="/User/Login" method="post"> <input type="submit" value="登入" /> </form>
後臺:
[HttpPost] public ActionResult Login(Models.User model) { if (model.UName == "lvhua" && model.UPWD == "123456") { return Redirect("/User/Index"); } Response.Write("<script>alert('用戶名或密碼錯誤');location.href='/User/Login'</script>"); return null; }
重定向
使用Return Redirect (路徑) ,至關於Response.Redirect
[HttpPost]和[HttpGet]
若是控制器中有兩個同名的Action方法時,應該用.net特性[HttpPost]和[HttpGet]區別
ActionResult和ViewResult
ViewResult 通常用於加載當前視圖
ActionResult 通常用於重定向
後臺接收前臺表單數據
前臺表單控件name命名與model屬性名相同,後臺Action方法參數中就能夠用model來接收了,服務器會把表單中的數據加進model裏
六,顯示Index.cshtml
前臺:
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <h3>Index</h3> <div> @for (int i = 1; i <= 10; i++) { <text>@i</text><span>只老虎</span> <a href="/User/Details/@i">進入</a><br /> } </div> </body> </html>
若是隻想顯示純文本,可用<text>標籤
七,顯示Details.cshtml
前臺:
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Details</title> </head> <body> <h3>Details</h3> <div> <span>第</span>@ViewBag.id<span>只老虎</span> </div> </body> </html>
後臺:
public ViewResult Details(int id) { ViewBag.id = id; return View(); }
後臺如何獲取跳轉的id?
前一個頁面,遵照RouteConfig的url格式
<a href="/User/Details/@i">進入</a><br />
後臺Action方法中參數id便可獲取(參數id名稱須與RouteConfig配置的id同名)