(五)ASP.NET MVC 中關於 Action 的參數

來源:互聯網
上載者:User

標籤: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 的參數

聯繫我們

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