關於MVC四種基本的表單傳輸方式
阿新 • • 發佈:2019-01-01
在mvc中如果檢視上有表單提交資料給後臺控制器,那麼後臺控制器如何進行獲取傳輸的資料呢!
在mvc中有最基本的四種資料傳輸方式,這裡不包括ajax非同步提交
首先咱們在檢視上實現一下表單提交功能,用來提交資料
所以需要一個form表單
1、設定表單提交到那個控制器(我這裡是Home控制器),在到該控制器中指定提交在那個方法裡面(我這裡是userinfor方法);再然後設定提交方式(我這裡post提交)。
2,再配置文字輸入框。
<form action="/Home/userinfor4" method="post"> <table> <tr> <td>使用者名稱:</td> <td><input type="text" name="name" /></td> </tr> <tr> <td>密碼:</td> <td><input type="password" name="password" /></td> </tr> <tr> <td>性別:</td> <td> <selectname="sex"> <option value="男">男</option> <option value="女">女</option> </select> </td> </tr> <tr> <td> <input type="submit" value="提交" /> </td> </tr> </table> </from>
3、進入到要提交的控制器裡面的方法,新增[HttpPost]過濾器
一、引數獲取傳輸的值;引數需要與表單中對應的name值
[HttpPost] public ActionResult userinfor(string name,string password,string sex) { return Content("姓名:"+name+" 密碼:"+password+" 性別:"+sex); //return View(); }
二、Request["key"]物件獲取傳輸的值
[HttpPost] public ActionResult userinfor() { return Content("姓名:" +Request["name"] + " 密碼:" +Request["password"] + " 性別:" + Request["sex"]); //return View(); }
三、使用類庫中的FormCollection類獲取傳輸的值
[HttpPost] public ActionResult userinfor(FormCollection user) { return Content("姓名:" + user["name"] + " 密碼:" + user["password"] + " 性別:" + user["sex"]); //return View(); }
四、在方法中引用自定義類,用自定義類中的欄位獲取(最常用的)
1、首先需要建立一個自定義類
public class UserInfor { public string name { get; set; } public string password { get; set; } public string sex { get; set; } }
2、然後再方法裡引用這個類
[HttpPost] public ActionResult userinfor4(UserInfor user) { return Content("姓名:" + user.name + " 密碼:" + user.password + " 性別:" + user.sex); //return View(); }