MVC 从后台页面 取前台页面表单传递过来的值的几种取法

<1>前台页面 Index视图

注意:用户名表单的name值为txtName
密码表单的name值为txtPassword

<html>  
<head>  
    <meta name="viewport" content="width=device-width" />  
    <title>Test</title>  
</head>  
<body>  
    <form action="/Home/Test" method="post">  
        <div>  
            <label>用户名</label><input type="text" name="txtName" />  
            <label>密 码</label><input type="text" name="txtPassword" />  
        </div>  
        <input type="submit" value="提交" />  
    </form>  
</body>  
</html>  

<2>后台页面,Home控制器

(为了测试,分别将视图页中的from表单的action设为 action="/Home/Test" ,action="/Home/Test2" action="/Home/Test3" action="/Home/Test4" )

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Web.Mvc;  
  
namespace MvcApplication1.Controllers  
{  
    public class HomeController : Controller  
    {  
        //  
        // GET: /Home/  
  
        public ActionResult Index()  
        {  
            return View();  
        }  
  
  
        // MVC第一种取值方式  
  
        public ActionResult Test()  
        {  
            string userName = Request["txtName"];   //此时Request["txtName"]=ABC  
            string password = Request["password"];  //此时Request["password"]=123  
  
            return Content("OK" + userName + password);  
        }  
  
        // 第二种取值方式  
  
        public ActionResult Test2(FormCollection f) //FormCollection是MVC中表单里的一个集合,它也可以来接收前台提交过来的表单,前台提交过来的表单全都封装到这个对象中来了  
        {  
            string userName = f["txtName"];     //此时f["txtName"]=ABC   
            string password = f["txtPassword"]; //此时f["txtPassword"]=123  
  
            return Content("OK" + userName + password);  
        }  
  
        // 第三种取值方式  
  
        public ActionResult Test3(string txtName, string txtPassword) //注意这个参数的名称必须要与前台页面控件的 name值是一致的  
        {  
            return Content("OK" + txtName + txtPassword);  
  
            //此时textName=ABC   
            //此时txtPassword=123  
        }  
  
  
        // 第四种取值方式,通过类对象接收  
  
        public ActionResult Test4(ParaClass p) //如果ParaClass类里面的属性与前台页面控件的name值一致,那么它的对象属性也会自动被赋值  
        {  
            return Content("OK" + p.txtName + p.txtPassword);  
  
            //此时p.txtName=ABC  
            //此时p.txtPassword=123  
        }  
  
  
        public class ParaClass  
        {  
            public string txtName { get; set; } //此时textName=ABC  
            public string txtPassword { get; set; } //此时txtPassword=123  
  
            //注意:ParaClass类的属性名称必须要与前端页面控件的name值一致,这样才能接收到前端页面传递过来的值  
        }  
        
    }  
}  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值