zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    hdoj--2098--分拆素数和(水题)
    hdoj--5563--Clarke and five-pointed star(简单几何)
    zzulioj--1813--good string(模拟)
    docker(3)docker下的centos7下安装jdk
    docker(2)安装centos7镜像与容器管理
    docker安装
    大数据简介
    esper(1)-窗口概述
    idea(2)快捷键
    idea(1)-idea初装
  • 原文地址:https://www.cnblogs.com/M-LittleBird/p/5855973.html
Copyright © 2011-2022 走看看