文章出處

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 
View Code

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         }
View Code

image

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         }
View Code

PersonViewModel類:

  1 public class PersonViewModel
  2     {
  3         public string Name { get; set; }
  4 
  5         public int Age { get; set; }
  6     }
View Code

image

image


文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()