標籤:result 返回 預設 div action person get 存在 元素
在ASP.NET MVC 的 Controller 類下有多個 Method,如果這些 Method 都是 public 修飾的和傳回值類型是 ActionResult 類型的,這些方法就時 Action。通過 “Controller 名字/方法名” 訪問的時候就會執行對應的方法。
Action 有三種類型的參數:普通參數,Model 類, FormCollection。
普通參數:構架會自動把使用者請求的值根據參數名字映射到對應的值。
Model 類:這種類叫 ViewModel
FormCollection:採用 fc["name"] 這種方式訪問,適用於表單元素不確定的情況
例如:在 cshtml 中有一個表單
<form action="Show" method="post"> <input type="text" name="Name" value="" /> <input type="text" name="Age" value="" /> <input type="submit" value="submit" /></form>
有一個類 Person:
public class Person{ public string Name { get; set; } public int Age { get; set; }}
在Controller 中 Action 的參數:
//參數名要跟表單中對應參數的 name 屬性一樣,但大小寫沒關係public ActionResult Show(string name, int age){ return Content(name + age) ;}
public ActionResult Show(Person p) { return Content(p.Name + p.Age) ; }
//fc 的索引名跟表單中對應參數的 name 屬性一樣,但大小寫沒關係public ActionResult Show(FormCollection fc) { string name = fc["Name"]; string age = fc["Age"]; return Content(name+age) ; }
Action 的方法不能重載,所以如果一個 Controller 中不能同時存在兩個相同的 Action
public ActionResult T1(){ return View(); }public ActionResult T1(Person p){ return View();}//以上兩個 Action 不能同時存在
但是如果給 Action方法標註上 [HttpGet], 和 [HttpPost] 的 Attribute,可以同時存在,這樣當頁面發出 Get 請求時執行標註 [HttpGet] 的方法,當發出 Post 請求的時候執行標註 [HttpPost] 的 Action。通常標註[HttpGet] 的 Action 用來展示初始頁面,標註 [HttpPost] 的 Action 用來處理表單提交。
[HttpGet]public ActionResult T1(){ return View(); }[HttpPost]public ActionResult T1(Person p){ //TODO:... return View();}
Action 的參數可以是一部分普通參數,一部分 Model:
public ActionResult T2(string adress, Person p){ //TODO:... return View(); }
Action 參數如果在請求中沒有對應的值,則 Model 類的形式會取預設值。如果是普通參數的形式會報錯,同時這個參數如果是實值型別,而且允許為空白,則要使用可空類型,或者使用 C# 的可以參數文法設定預設值。
//public ActionResult T1(string name, int? age)//{}////或者////public ActionResult T1(string name, int age = 0)//{}
對於在 ASP.NET MVC 中上傳檔案,參數使用 HttpPostedFileBase 類型,同時在 form 表單中有 enctype="multipart/form-data 這個屬性。
(五)ASP.NET MVC 中關於 Action 的參數