日期:2014-06-10  浏览次数:20691 次

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

1、新建一个mvc项目如:

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

 

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"]为获取视图数据字典)  

  

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默认视图 

 

@{
    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

 

@{
    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、运行结果

 

 

百度盘下载 点击下载