关于MVC四种基本的表单传输方式

在mvc中如果视图上有表单提交数据给后台控制器,那么后台控制器如何进行获取传输的数据呢!

在mvc中有最基本的四种数据传输方式,这里不包括ajax异步提交

首先咱们在视图上实现一下表单提交功能,用来提交数据

所以需要一个form表单

1、设置表单提交到那个控制器(我这里是Home控制器),在到该控制器中指定提交在那个方法里面(我这里是userinfor方法);再然后设置提交方式(我这里post提交)。

2,再配置文本输入框。

<form action="/Home/userinfor4" method="post">
    <table>
        <tr>
            <td>用户名:</td>
            <td><input type="text" name="name" /></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><input type="password" name="password" /></td>
        </tr>
        <tr>
            <td>性别:</td>
            <td>
                <select name="sex">
                    <option value="">男</option>
                    <option value="">女</option>
                </select>
            </td>
        </tr>
        <tr>
            <td>
                <input type="submit" value="提交" />
            </td>
        </tr>
    </table>
    </from>

3、进入到要提交的控制器里面的方法,添加[HttpPost]过滤器

一、参数获取传输的值;参数需要与表单中对应的name值

        [HttpPost]
        public ActionResult userinfor(string name,string password,string sex)
        {
            return Content("姓名:"+name+"   密码:"+password+"  性别:"+sex);
            //return View();
        }

二、Request["key"]对象获取传输的值

        [HttpPost]
        public ActionResult userinfor()
        {
            return Content("姓名:" +Request["name"]  + "   密码:" +Request["password"] + "  性别:" + Request["sex"]);
            //return View();
        }

三、使用类库中的FormCollection类获取传输的值

        [HttpPost]
        public ActionResult userinfor(FormCollection user)
        {
            return Content("姓名:" + user["name"] + "   密码:" + user["password"] + "  性别:" + user["sex"]);
            //return View();
        }

四、在方法中引用自定义类,用自定义类中的字段获取(最常用的)

     1、首先需要建立一个自定义类

        public class UserInfor
        {
            public string name { get; set; }
            public string password { get; set; }
            public string sex { get; set; }
        }

    2、然后再方法里引用这个类

        [HttpPost]
        public ActionResult userinfor4(UserInfor user)
        {
            return Content("姓名:" + user.name + "   密码:" + user.password + "  性别:" + user.sex);
            //return View();
        }

猜你喜欢

转载自www.cnblogs.com/live8/p/10204638.html
今日推荐