標籤:blog class code tar ext c
第一次寫記錄文章,難免有不足之處;歡迎指出。
1、建立一個mvc項目如:
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、運行結果
百度盤下載 點擊下載