練習:
新建一個mvc項目
要求:
有3個視圖 Login Index Details
目的:
感受一下MVC與傳統WebForm的差異性
WebForm的請求模型
MVC請求模型
傳統WebForm與MVC區別
WebForm 實際上請求的是一個頁面對象
MVC 不僅請求了一個頁面對象,還向服務器請求了具體的業務處理方法
程序結構如下
一,項目模板和視圖引擎介紹
項目模板
基本: 一般選擇這個 它會自動將一些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同名)