文章出處
View Code
View Code
View Code
View Code
文章列表
1.在控制器中建立一個PostDemo方法,建立視圖創建一個表單

1 <h2>PostDemo</h2> 2 name的值:@ViewBag.name 3 <br /> 4 name2的值:@ViewBag.name2 5 <form action="/RequestDemo/PostDemo" method="post"> 6 <input type="text" id="name" name="name"/> 7 <input type="submit" value="提交"/> 8 </form> 9 實體方式提交: 10 <form action="/RequestDemo/PostDemomodel" method="post"> 11 <input type="text" id="name" name="name" /> 12 <input type="submit" value="提交" /> 13 </form> 14
2.然后建立一個和PostDemo方法同名的方法,標記為httpPost請求,參數為FormCollection類型,表示是獲取提交保單所有的數據

1 //默認為Get方法請求 2 public ActionResult PostDemo() 3 { 4 return View(); 5 } 6 //標記為Post方式請求,改方法就只能接受post方法請求 7 [HttpPost] 8 public ActionResult PostDemo(FormCollection form) 9 { 10 //第一種獲取提交表單的方式 11 string name = Request.Form["name"]; 12 ViewBag.name = name; 13 //第二種獲取提交表單的方式 14 string name2 = form["name"]; 15 ViewBag.name2 = name2; 16 return View(); 17 }
3.第三種寫法是使用一個類來接收數據,同樣也要標記HttpPost,這里是MVC自動把表單中名稱跟PersonViewModel類中同名的屬性復制,注意必須:前臺提交的input標簽中的text元素名是name和PersonViewModel類的屬性名稱相同。

1 [HttpPost] 2 public ActionResult PostDemomodel(PersonViewModel model) 3 { 4 //使用model方式提交 5 string name = model.Name; 6 ViewBag.name = name; 7 8 return View("PostDemo"); 9 }
PersonViewModel類:

1 public class PersonViewModel 2 { 3 public string Name { get; set; } 4 5 public int Age { get; set; } 6 }
文章列表
全站熱搜