日期:17-3-7
控制器三個約定:
- 控制器命名規範:"NameController",以Controller結尾
- 控制器必須是非靜态類
-
實作IController接口(多次繼承)
控制器裡面的方法都被稱為Action
Views檔案夾下面會根據Controller名建立若幹個以Controller命名的檔案夾,該檔案夾下還能,隻能建立一個檔案夾“Shared”,以及一個系統生成的web.config。
添加視圖:在Controller的方法名上右擊添加視圖
WebForm與Asp.net MVC請求頁面的差別:
<b>webForm</b>請求的是一個aspx頁面。
http://localhost/a.aspx<b>
Asp.netMVC</b> 請求位址,請求控制器裡面的方法。
http://localhost/Home/index使用者 > Controller-Action > ViewData資料-View
Action:
- 處理使用者的請求,Request,Response
- 調用業務邏輯(Model BLL DAL)
- 把資料傳遞給View進行展示
ViewData[]從Controller向View傳遞資料
Action 如果沒有指定(return View("index");)對應的視圖來展示資料的話,預設是尋找跟Action同名的View進行展示。一般Action名與指定的視圖同名。
前台表單代碼
<form action="/UserInfo/ProcessUserInfo" method="post">
<div class="form-group">
<label for="UserName">UserName</label>
<input type="text" class="form-control" name="txtName" id="UserName" placeholder="請輸入使用者名">
</div>
<div class="form-group">
<label for="Pwd">Password</label>
<input type="password" class="form-control" name="txtPwd" id="Pwd" placeholder="請輸入密碼">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
從前台擷取資料的四種方式
方式一
public ActionResult ProcessUserInfo()
{
string UserName = Request["txtName"];//與前台name同名。對于表單form,隻有設定了 name 屬性的表單元素才能在送出表單時傳遞它們的值。
string UserPwd = Request["txtPwd"];
return Content("OK" + "</br>" + UserName + "</br>" + UserPwd);
}
方式二
public ActionResult ProcessUserInfo(FormCollection collection)
{
string str = collection["txtName"];
string pwd=collection["txtPwd"];
return Content("OK" + "</br>" + str+ "</br>" + pwd
}
方式三
public ActionResult ProcessUserInfo(string txtName,string txtPwd)//與前台name同名
{
return Content("OK" + "</br>" + txtName + "</br>" + txtPwd)
}
方式四
public class Info
{
public string txtName { get; set; } //與前台name同名
public string txtPwd { get; set; }
}
public ActionResult ProcessUserInfo(Info userA)
{
return Content("OK" + "</br>" + userA.txtName,string + "</br>" + userA.txtPwd)
}
HtmlHelper
超連結的三種形式
超連結方式1
<a href="/Home/About">連結到About頁面</a>
<br/>
超連結方式2
這種方式避免了上面更改路由機制之後要更改所有的連結代碼
<br/>
<a [email protected]("About","Home")>連結到About</a>
<br/>
超連結方式3
<br/>
@Html.ActionLink("About頁面","About","Home",null,new { style = "Color:green" ,@class="aaa"}) 設定htmlAttr