asp.net MVC中控制器获取表单form提交的数据之实体类数据

时间:2014-05-11 17:18:55   收藏:0   阅读:517

第一次写记录文章,难免有不足之处;欢迎指出。

1、新建一个mvc项目如:

bubuko.com,布布扣

2、新建一个Test.cs 注意get,set方法不能简写

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace Models
{
    [Serializable]
    public class Test
    {
        private int id;
 
        public int Id
        {
            get { return id; }
            set { id = value; }
        }
        private string name;
 
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        private string password;
 
        public string Password
        {
            get { return password; }
            set { password = value; }
        }
        private string age;
 
        public string Age
        {
            get { return age; }
            set { age = value; }
        }
    }
}

  

 

3、建一个控制器 HomeController.cs

  新建一个ActionResult Test(Test t) 其中参数为Test实体类

  ViewData["Test"] = t; 

  赋值t到数据字典传给Test.cshtml视图页面

  (ViewData["Test"]为获取或设置视图的数据字典,ViewBag["Test"]为获取视图数据字典)  

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace MvcForm.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
         
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Test(Test t)
        {
            ViewData["Test"] = t;
            return View("Test");
        }
    }
}

  

4、新建一个提交form默认视图 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Home</title>
</head>
<body>
    <div>
        <form action="/Home/Test" method="post">
            <input type="text" name="id" /><br />
            <input type="text" name="name" /><br />
            <input type="text" name="password" /><br />
            <input type="submit" />
        </form>
    </div>
</body>
</html>

  

  

5、新建一个接受数据的视图 Test.cshtml

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@{
    Layout = null;
}
@using Models;
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Test</title>
</head>
<body>
    <div>
        @{
            Test t = (Test)ViewData["Test"];
         }
        id:@t.Id
        name:@t.Name
        password:@t.Password
        
    </div>
</body>
</html>

  

  

6、运行结果

 

bubuko.com,布布扣

bubuko.com,布布扣

 

百度盘下载 点击下载

 

asp.net MVC中控制器获取表单form提交的数据之实体类数据,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!