ASP.NET MVC post请求接收参数的三种方式

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

原文地址:https://www.cnblogs.com/shiyh/p/8820993.html