【ASP.NET MVC】View与Controller之间传递数据

1   概述

本篇文章主要从操作上简要分析Controller<=>View之间相互传值,关于页面之间传值,如果感兴趣,可参考我另外一篇文章ASP.NET 页面之间传值的几种方式 。

Controller=》View:Model,ViewBag,ViewData,TempData,ViewBag=>ViewData,ViewData=>ViewBag,ViewModel,JqGrid,AJAX+第三方插件等;

View=》Controller:QueryString,Form,FormCollection,Ajax,自定义模型绑定等;

2   Controller向View传递数据

2.1  Model传递数据

(1)DB表:

(2)Model

 1 public class CustomerInfo
 2     {
 3         public string EmployeeID { get; set; }
 4         public string EmployeeName { get; set; }
 5         public string EmployeeMajor { get; set; }
 6         public string EmployeeDepartment { get; set; }
 7         public string EmployeeTel { get; set; }
 8         public string EmployeeEmail { get; set; }
 9         public string EmployeeJiGuan { get; set; }
10         public string EmployeeAddress { get; set; }
11         public string EmployeePosition { get; set; }
12         public string EmployeeBirthday { get; set; }
13     }

(3)Controller

a.控制器action

public ActionResult ModelDataToView()
        {
            //定义集合
            List<CustomerInfo> ltPI = new List<CustomerInfo>();
            DataTable dt = GetCustomerInfoToDataTable();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                CustomerInfo custInfo = new CustomerInfo();
                custInfo.EmployeeID = dt.Rows[i]["EmployeeID"].ToString();
                custInfo.EmployeeName = dt.Rows[i]["EmployeeName"].ToString();
                custInfo.EmployeeMajor = dt.Rows[i]["EmployeeMajor"].ToString();
                custInfo.EmployeeDepartment = dt.Rows[i]["EmployeeDepartment"].ToString();
                custInfo.EmployeeTel = dt.Rows[i]["EmployeeTel"].ToString();
                custInfo.EmployeeEmail = dt.Rows[i]["EmployeeEmail"].ToString();
                custInfo.EmployeeJiGuan = dt.Rows[i]["EmployeeJiGuan"].ToString();
                custInfo.EmployeeAddress = dt.Rows[i]["EmployeeAddress"].ToString();
                custInfo.EmployeePosition = dt.Rows[i]["EmployeePosition"].ToString();
                custInfo.EmployeeBirthday = dt.Rows[i]["EmployeeBirthday"].ToString();
                ltPI.Add(custInfo);
            }
          return View("Index",ltPI);
        }

b.ADO.NET 获取CustomerInfo数据

 1 //获取用户实体
 2         public DataTable GetCustomerInfoToDataTable()
 3         {
 4             //连接字符串
 5             string conStr = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
 6             string strSql = @"SELECT * FROM EmployeeInfo";
 7             using (SqlConnection conn = new SqlConnection(conStr))
 8             {
 9                 conn.Open();
10                 SqlCommand cmd = new SqlCommand(strSql, conn);
11                 cmd.ExecuteNonQuery();
12                 SqlDataAdapter sda = new SqlDataAdapter(strSql, conn);
13                 DataSet ds = new DataSet();
14                 sda.Fill(ds,"CustomerInfo");
15                 return ds.Tables["CustomerInfo"];
16             }
17         }

(4)View

 1 @{
 2     Layout = null;
 3 }
 4
 5 <!DOCTYPE html>
 6
 7 <html>
 8 <head>
 9     <meta name="viewport" content="width=device-width" />
10     <link href="~/OuterLibrary/jquery-ui-themes-1.12.1/jquery-ui.css" rel="stylesheet" />
11     <link href="~/OuterLibrary/bootstrap/bootstrap/css/bootstrap.css" rel="stylesheet" />
12     <link href="~/OuterLibrary/bootstrap/bootstrap/css/bootstrap-responsive.css" rel="stylesheet" />
13     <script src="~/OuterLibrary/Jquery/jquery-3.2.1.js"></script>
14     <script src="~/OuterLibrary/bootstrap/bootstrap/js/bootstrap.js"></script>
15     <title>Index</title>
16 </head>
17 <body>
18     <div class="table-responsive">
19        <table class="table table-striped">
20                 <thead>
21                    <tr>
22                         <td>员工ID</td>
23                         <td>员工姓名</td>
24                         <td>员工专业</td>
25                         <td>员工部门</td>
26                         <td>员工电话</td>
27                         <td>员工邮件</td>
28                         <td>员工籍贯</td>
29                         <td>员工住址</td>
30                         <td>员工职位</td>
31                         <td>员工生日</td>
32                     </tr>
33                 </thead>
34                 <tbody>
35                     @foreach (var item in Model)
36                     {
37                         <tr>
38                             <td>@item.EmployeeID</td>
39                             <td>@item.EmployeeName</td>
40                             <td>@item.EmployeeMajor</td>
41                             <td>@item.EmployeeDepartment</td>
42                             <td>@item.EmployeeTel</td>
43                             <td>@item.EmployeeEmail</td>
44                             <td>@item.EmployeeJiGuan</td>
45                             <td>@item.EmployeeAddress</td>
46                             <td>@item.EmployeePosition</td>
47                             <td>@item.EmployeeBirthday</td>
48                         </tr>
49                     }
50                 </tbody>
52             </table>
53    </div>
54 </body>
55 </html>

(5)结果

2.2  ViewData传递数据

(1)DB表:

(2)Model

 1 public class CustomerInfo
 2     {
 3         public string EmployeeID { get; set; }
 4         public string EmployeeName { get; set; }
 5         public string EmployeeMajor { get; set; }
 6         public string EmployeeDepartment { get; set; }
 7         public string EmployeeTel { get; set; }
 8         public string EmployeeEmail { get; set; }
 9         public string EmployeeJiGuan { get; set; }
10         public string EmployeeAddress { get; set; }
11         public string EmployeePosition { get; set; }
12         public string EmployeeBirthday { get; set; }
13     }

(3)Controller

a.控制器action

 1  //ViewData传递
 2         public ActionResult ViewDataToView()
 3         {
 4             List<CustomerInfo> ltPI = new List<CustomerInfo>();
 5             DataTable dt = GetCustomerInfoToDataTable();
 6             for (int i = 0; i < dt.Rows.Count; i++)
 7             {
 8                 CustomerInfo custInfo = new CustomerInfo();
 9                 custInfo.EmployeeID = dt.Rows[i]["EmployeeID"].ToString();
10                 custInfo.EmployeeName = dt.Rows[i]["EmployeeName"].ToString();
11                 custInfo.EmployeeMajor = dt.Rows[i]["EmployeeMajor"].ToString();
12                 custInfo.EmployeeDepartment = dt.Rows[i]["EmployeeDepartment"].ToString();
13                 custInfo.EmployeeTel = dt.Rows[i]["EmployeeTel"].ToString();
14                 custInfo.EmployeeEmail = dt.Rows[i]["EmployeeEmail"].ToString();
15                 custInfo.EmployeeJiGuan = dt.Rows[i]["EmployeeJiGuan"].ToString();
16                 custInfo.EmployeeAddress = dt.Rows[i]["EmployeeAddress"].ToString();
17                 custInfo.EmployeePosition = dt.Rows[i]["EmployeePosition"].ToString();
18                 custInfo.EmployeeBirthday = dt.Rows[i]["EmployeeBirthday"].ToString();
19                 ltPI.Add(custInfo);
20                 ViewData["CustomerInfo"] = ltPI;
21             }
22             return View();
23         }

b.ADO.NET 获取CustomerInfo数据

 1 //获取用户实体
 2         public DataTable GetCustomerInfoToDataTable()
 3         {
 4             //连接字符串
 5             string conStr = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
 6             string strSql = @"SELECT * FROM EmployeeInfo";
 7             using (SqlConnection conn = new SqlConnection(conStr))
 8             {
 9                 conn.Open();
10                 SqlCommand cmd = new SqlCommand(strSql, conn);
11                 cmd.ExecuteNonQuery();
12                 SqlDataAdapter sda = new SqlDataAdapter(strSql, conn);
13                 DataSet ds = new DataSet();
14                 sda.Fill(ds,"CustomerInfo");
15                 return ds.Tables["CustomerInfo"];
16             }
17         }

(4)View

 1 @using MVCCrud.Areas.JqGridDemo.Models
 2
 3
 4 @{
 5     Layout = null;
 6 }
 7
 8 <!DOCTYPE html>
 9
10 <html>
11 <head>
12     <meta name="viewport" content="width=device-width" />
13     <link href="~/OuterLibrary/jquery-ui-themes-1.12.1/jquery-ui.css" rel="stylesheet" />
14     <link href="~/OuterLibrary/bootstrap/bootstrap/css/bootstrap.css" rel="stylesheet" />
15     <link href="~/OuterLibrary/bootstrap/bootstrap/css/bootstrap-responsive.css" rel="stylesheet" />
16     <script src="~/OuterLibrary/Jquery/jquery-3.2.1.js"></script>
17     <script src="~/OuterLibrary/bootstrap/bootstrap/js/bootstrap.js"></script>
18     <title>ViewDataToView</title>
19 </head>
20 <body>
21     <div class="table-responsive">
22         <table class="table table-striped">
23             <thead>
24                 <tr>
25                     <td>员工ID</td>
26                     <td>员工姓名</td>
27                     <td>员工专业</td>
28                     <td>员工部门</td>
29                     <td>员工电话</td>
30                     <td>员工邮件</td>
31                     <td>员工籍贯</td>
32                     <td>员工住址</td>
33                     <td>员工职位</td>
34                     <td>员工生日</td>
35                 </tr>
36             </thead>
37             <tbody>
38                 @foreach (var item in (List<CustomerInfo>)ViewData["CustomerInfo"])
39                 {
40                     <tr>
41                         <td>@item.EmployeeID</td>
42                         <td>@item.EmployeeName</td>
43                         <td>@item.EmployeeMajor</td>
44                         <td>@item.EmployeeDepartment</td>
45                         <td>@item.EmployeeTel</td>
46                         <td>@item.EmployeeEmail</td>
47                         <td>@item.EmployeeJiGuan</td>
48                         <td>@item.EmployeeAddress</td>
49                         <td>@item.EmployeePosition</td>
50                         <td>@item.EmployeeBirthday</td>
51                     </tr>
52                 }
53
54             </tbody>
55         </table>
56     </div>
57 </body>
58 </html>

(5)结果

2.3  ViewBag传递数据

(1)DB表:

(2)Model

 1 public class CustomerInfo
 2     {
 3         public string EmployeeID { get; set; }
 4         public string EmployeeName { get; set; }
 5         public string EmployeeMajor { get; set; }
 6         public string EmployeeDepartment { get; set; }
 7         public string EmployeeTel { get; set; }
 8         public string EmployeeEmail { get; set; }
 9         public string EmployeeJiGuan { get; set; }
10         public string EmployeeAddress { get; set; }
11         public string EmployeePosition { get; set; }
12         public string EmployeeBirthday { get; set; }
13     }

(3)Controller

a.控制器action

 1 //ViewBag传递
 2         public ActionResult ViewBagDataToView()
 3         {
 4             List<CustomerInfo> ltPI = new List<CustomerInfo>();
 5             DataTable dt = GetCustomerInfoToDataTable();
 6             for (int i = 0; i < dt.Rows.Count; i++)
 7             {
 8                 CustomerInfo custInfo = new CustomerInfo();
 9                 custInfo.EmployeeID = dt.Rows[i]["EmployeeID"].ToString();
10                 custInfo.EmployeeName = dt.Rows[i]["EmployeeName"].ToString();
11                 custInfo.EmployeeMajor = dt.Rows[i]["EmployeeMajor"].ToString();
12                 custInfo.EmployeeDepartment = dt.Rows[i]["EmployeeDepartment"].ToString();
13                 custInfo.EmployeeTel = dt.Rows[i]["EmployeeTel"].ToString();
14                 custInfo.EmployeeEmail = dt.Rows[i]["EmployeeEmail"].ToString();
15                 custInfo.EmployeeJiGuan = dt.Rows[i]["EmployeeJiGuan"].ToString();
16                 custInfo.EmployeeAddress = dt.Rows[i]["EmployeeAddress"].ToString();
17                 custInfo.EmployeePosition = dt.Rows[i]["EmployeePosition"].ToString();
18                 custInfo.EmployeeBirthday = dt.Rows[i]["EmployeeBirthday"].ToString();
19                 ltPI.Add(custInfo);
20                 ViewBag.CustomerInfo = ltPI;
21             }
22             return View();
23         }

b.ADO.NET 获取CustomerInfo数据

 1 //获取用户实体
 2         public DataTable GetCustomerInfoToDataTable()
 3         {
 4             //连接字符串
 5             string conStr = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
 6             string strSql = @"SELECT * FROM EmployeeInfo";
 7             using (SqlConnection conn = new SqlConnection(conStr))
 8             {
 9                 conn.Open();
10                 SqlCommand cmd = new SqlCommand(strSql, conn);
11                 cmd.ExecuteNonQuery();
12                 SqlDataAdapter sda = new SqlDataAdapter(strSql, conn);
13                 DataSet ds = new DataSet();
14                 sda.Fill(ds,"CustomerInfo");
15                 return ds.Tables["CustomerInfo"];
16             }
17         }

(4)View

 1 @{
 2     Layout = null;
 3 }
 4
 5 <!DOCTYPE html>
 6
 7 <html>
 8 <head>
 9     <meta name="viewport" content="width=device-width" />
10     <link href="~/OuterLibrary/jquery-ui-themes-1.12.1/jquery-ui.css" rel="stylesheet" />
11     <link href="~/OuterLibrary/bootstrap/bootstrap/css/bootstrap.css" rel="stylesheet" />
12     <link href="~/OuterLibrary/bootstrap/bootstrap/css/bootstrap-responsive.css" rel="stylesheet" />
13     <script src="~/OuterLibrary/Jquery/jquery-3.2.1.js"></script>
14     <script src="~/OuterLibrary/bootstrap/bootstrap/js/bootstrap.js"></script>
15     <title>ViewBagDataToView</title>
16 </head>
17 <body>
18     <div class="table-responsive">
19         <table class="table table-striped">
20             <thead>
21                 <tr>
22                     <td>员工ID</td>
23                     <td>员工姓名</td>
24                     <td>员工专业</td>
25                     <td>员工部门</td>
26                     <td>员工电话</td>
27                     <td>员工邮件</td>
28                     <td>员工籍贯</td>
29                     <td>员工住址</td>
30                     <td>员工职位</td>
31                     <td>员工生日</td>
32                 </tr>
33             </thead>
34             <tbody>
35                 @foreach (var item in ViewBag.CustomerInfo)
36                 {
37                     <tr>
38                         @*<td>@item.Em</td>*@
39                         <td>@item.EmployeeName</td>
40                         <td>@item.EmployeeMajor</td>
41                         <td>@item.EmployeeDepartment</td>
42                         <td>@item.EmployeeTel</td>
43                         <td>@item.EmployeeEmail</td>
44                         <td>@item.EmployeeJiGuan</td>
45                         <td>@item.EmployeeAddress</td>
46                         <td>@item.EmployeePosition</td>
47                         <td>@item.EmployeeBirthday</td>
48                     </tr>
49                 }
50
51             </tbody>
52         </table>
53
54     </div>
55 </body>
56 </html>

(4)View

 1 @using MVCCrud.Areas.JqGridDemo.Models
 2
 3 @{
 4     Layout = null;
 5 }
 6
 7 <!DOCTYPE html>
 8
 9 <html>
10 <head>
11     <meta name="viewport" content="width=device-width" />
12     <link href="~/OuterLibrary/jquery-ui-themes-1.12.1/jquery-ui.css" rel="stylesheet" />
13     <link href="~/OuterLibrary/bootstrap/bootstrap/css/bootstrap.css" rel="stylesheet" />
14     <link href="~/OuterLibrary/bootstrap/bootstrap/css/bootstrap-responsive.css" rel="stylesheet" />
15     <script src="~/OuterLibrary/Jquery/jquery-3.2.1.js"></script>
16     <script src="~/OuterLibrary/bootstrap/bootstrap/js/bootstrap.js"></script>
17     <title>ViewBagDataToView</title>
18 </head>
19 <body>
20     <div class="table-responsive">
21         <table class="table table-striped">
22             <thead>
23                 <tr>
24                     <td>员工ID</td>
25                     <td>员工姓名</td>
26                     <td>员工专业</td>
27                     <td>员工部门</td>
28                     <td>员工电话</td>
29                     <td>员工邮件</td>
30                     <td>员工籍贯</td>
31                     <td>员工住址</td>
32                     <td>员工职位</td>
33                     <td>员工生日</td>
34                 </tr>
35             </thead>
36             <tbody>
37                 @foreach (var item in (List<CustomerInfo>)TempData["CustomerInfo"])
38                 {
39                     <tr>
40                         <td>@item.EmployeeID</td>
41                         <td>@item.EmployeeName</td>
42                         <td>@item.EmployeeMajor</td>
43                         <td>@item.EmployeeDepartment</td>
44                         <td>@item.EmployeeTel</td>
45                         <td>@item.EmployeeEmail</td>
46                         <td>@item.EmployeeJiGuan</td>
47                         <td>@item.EmployeeAddress</td>
48                         <td>@item.EmployeePosition</td>
49                         <td>@item.EmployeeBirthday</td>
50                     </tr>
51                 }
52
53             </tbody>
54         </table>
55     </div>
56 </body>
57 </html>

(5)结果

2.4  TempData传递数据

(1)DB表:

(2)Model

 1  public class CustomerInfo
 2     {
 3         public string EmployeeID { get; set; }
 4         public string EmployeeName { get; set; }
 5         public string EmployeeMajor { get; set; }
 6         public string EmployeeDepartment { get; set; }
 7         public string EmployeeTel { get; set; }
 8         public string EmployeeEmail { get; set; }
 9         public string EmployeeJiGuan { get; set; }
10         public string EmployeeAddress { get; set; }
11         public string EmployeePosition { get; set; }
12         public string EmployeeBirthday { get; set; }
13     }

(3)Controller

a.action

 1  //TempData传递数据
 2         public ActionResult TempDataToView()
 3         {
 4             List<CustomerInfo> ltPI = new List<CustomerInfo>();
 5             DataTable dt = GetCustomerInfoToDataTable();
 6             for (int i = 0; i < dt.Rows.Count; i++)
 7             {
 8                 CustomerInfo custInfo = new CustomerInfo();
 9                 custInfo.EmployeeID = dt.Rows[i]["EmployeeID"].ToString();
10                 custInfo.EmployeeName = dt.Rows[i]["EmployeeName"].ToString();
11                 custInfo.EmployeeMajor = dt.Rows[i]["EmployeeMajor"].ToString();
12                 custInfo.EmployeeDepartment = dt.Rows[i]["EmployeeDepartment"].ToString();
13                 custInfo.EmployeeTel = dt.Rows[i]["EmployeeTel"].ToString();
14                 custInfo.EmployeeEmail = dt.Rows[i]["EmployeeEmail"].ToString();
15                 custInfo.EmployeeJiGuan = dt.Rows[i]["EmployeeJiGuan"].ToString();
16                 custInfo.EmployeeAddress = dt.Rows[i]["EmployeeAddress"].ToString();
17                 custInfo.EmployeePosition = dt.Rows[i]["EmployeePosition"].ToString();
18                 custInfo.EmployeeBirthday = dt.Rows[i]["EmployeeBirthday"].ToString();
19                 ltPI.Add(custInfo);
20                 TempData["CustomerInfo"] = ltPI;
21             }
22             return View();
23         }

b.ADO.NET 获取CustomerInfo数据

 1  //获取用户实体
 2         public DataTable GetCustomerInfoToDataTable()
 3         {
 4             //连接字符串
 5             string conStr = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
 6             string strSql = @"SELECT * FROM EmployeeInfo";
 7             using (SqlConnection conn = new SqlConnection(conStr))
 8             {
 9                 conn.Open();
10                 SqlCommand cmd = new SqlCommand(strSql, conn);
11                 cmd.ExecuteNonQuery();
12                 SqlDataAdapter sda = new SqlDataAdapter(strSql, conn);
13                 DataSet ds = new DataSet();
14                 sda.Fill(ds,"CustomerInfo");
15                 return ds.Tables["CustomerInfo"];
16             }
17         }

(5)结果

2.5 第三方插件

JqGrid插件:

控制器:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Mvc;
 6
 7 namespace MVCCrud.Areas.JqGridDemo.Controllers
 8 {
 9     public class JqGridCustomerInfoController : Controller
10     {
11         // GET: JqGridDemo/JqGridCustomerInfo
12         public ActionResult Index()
13         {
14             return View();
15         }
16     }
17 }

视图:

  1 @{
  2     Layout = null;
  3 }
  4
  5 <!DOCTYPE html>
  6
  7 <html>
  8 <head>
  9     <meta name="viewport" content="width=device-width" />
 10     <link href="~/OuterLibrary/jquery-ui-themes-1.12.1/jquery-ui.css" rel="stylesheet" />
 11     <link href="~/OuterLibrary/jquery-ui-themes-1.12.1/jquery-ui.theme.css" rel="stylesheet" />
 12     <link href="~/OuterLibrary/tonytomov-jqGrid-6659334/css/ui.jqgrid.css" rel="stylesheet" />
 13     <script src="~/OuterLibrary/Jquery/jquery-3.2.1.js"></script>
 14     <script src="~/OuterLibrary/tonytomov-jqGrid-6659334/js/i18n/grid.locale-en.js"></script>
 15     <script src="~/OuterLibrary/tonytomov-jqGrid-6659334/js/jquery.jqGrid.js"></script>
 16     <title>Index</title>
 17 </head>
 18 <body>
 19     <div>
 20         <div class="main" id="main">
 21             <table id="JqGrid-table"></table>
 22             <div id="JqGrid-pager"></div>
 23        </div>
 24        <script type="text/javascript">
 25            $("#JqGrid-table").jqGrid({
 26                 url: "/JqGridDemo/JsonDemo/Index",
 27                 datatype: "json",
 28                 height: 150,
 29                 mtype: "Get",
 30                 colNames: [‘员工ID‘, ‘员工姓名‘, ‘员工专业‘, ‘员工部门‘, ‘员工电话‘,‘员工邮件‘,‘员工籍贯‘,‘员工住址‘,‘员工职位‘,‘员工生日‘],
 31                 colModel: [{
 32                     name: ‘EmployeeID‘,
 33                     index: ‘EmployeeID‘,
 34                     key: true,
 35                     width: 100,
 36                     editable: false,
 37                     editoptions: {
 38                         size: "20",
 39                         maxlength: "30"
 40                     }
 41                 }, {
 42                     name: ‘EmployeeName‘,
 43                     index: ‘EmployeeName‘,
 44                     width: 200,
 45                     editable: false,
 46                     edittype: false,
 47                     editoptions: {
 48                         size: "20",
 49                         maxlength: "30"
 50                     }
 51                     }, {
 52                         name: ‘EmployeeMajor‘,
 53                         index: ‘EmployeeMajor‘,
 54                         width: 200,
 55                         editable: false,
 56                         edittype: false,
 57                         editoptions: {
 58                             size: "20",
 59                             maxlength: "30"
 60                         }
 61                     },
 62                     {
 63                         name: ‘EmployeeDepartment‘,
 64                         index: ‘EmployeeDepartment‘,
 65                         width: 200,
 66                         editable: false,
 67                         edittype: false,
 68                         editoptions: {
 69                             size: "20",
 70                             maxlength: "30"
 71                         }
 72                     }, {
 73                         name: ‘EmployeeTel‘,
 74                         index: ‘EmployeeTel‘,
 75                         width: 200,
 76                         editable: false,
 77                         edittype: false,
 78                         editoptions: {
 79                             size: "20",
 80                             maxlength: "30"
 81                         }
 82                     }, {
 83                         name: ‘EmployeeEmail‘,
 84                         index: ‘EmployeeEmail‘,
 85                         width: 200,
 86                         editable: false,
 87                         edittype: false,
 88                         editoptions: {
 89                             size: "20",
 90                             maxlength: "30"
 91                         }
 92                     }, {
 93                         name: ‘EmployeeJiGuan‘,
 94                         index: ‘EmployeeJiGuan‘,
 95                         width: 200,
 96                         editable: false,
 97                         edittype: false,
 98                         editoptions: {
 99                             size: "20",
100                             maxlength: "30"
101                         }
102                     }, {
103                         name: ‘EmployeeAddress‘,
104                         index: ‘EmployeeAddress‘,
105                         width: 200,
106                         editable: false,
107                         edittype: false,
108                         editoptions: {
109                             size: "20",
110                             maxlength: "30"
111                         }
112                     }, {
113                         name: ‘EmployeePosition‘,
114                         index: ‘EmployeePosition‘,
115                         width: 200,
116                         editable: false,
117                         edittype: false,
118                         editoptions: {
119                             size: "20",
120                             maxlength: "30"
121                         }
122                     }, {
123                         name: ‘EmployeeBirthday‘,
124                         index: ‘EmployeeBirthday‘,
125                         width: 200,
126                         editable: false,
127                         edittype: false,
128                         editoptions: {
129                             size: "20",
130                             maxlength: "30"
131                         }
132                     },  ],
133                 viewrecords: true,
134                 rowNum: 10,
135                 rowList: [10, 20, 30],
136                 pager: ‘#JqGrid-pager‘,
137                 altRows: true,
138                 multiselect: true,
139                 multiboxonly: true,
140                 caption: "员工信息表",
141                 autowidth: true
142             });
143              jQuery("#grid-table").jqGrid(‘navGrid‘, ‘#grid-pager‘, { edit: true, add: true, del: true });
144         </script>
145     </div>
146 </body>
147 </html>

控制器:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Helpers;
 6 using System.Web.Mvc;
 7 using System.Web.Script.Serialization;
 8
 9 namespace MVCCrud.Areas.JqGridDemo.Controllers
10 {
11     public class JsonDemoController : Controller
12     {
13         // GET: JqGridDemo/JsonDemo
14
15         public ActionResult Index()
16         {
17             var jsondata = new[]
18             {
19                new{
20                     EmployeeID = "NX0001",
21                     EmployeeName = "张三",
22                     EmployeeMajor = "金融学",
23                     EmployeeDepartment = "风投部门",
24                     EmployeeTel = "XXX",
25                     EmployeeEmail="[email protected]",
26                     EmployeeJiGuan="上海",
27                     EmployeeAddress="上海浦东新区",
28                     EmployeePosition="高级软件工程师",
29                     EmployeeBirthday="XXX",
30                   }
31             };
32              return Json(jsondata,JsonRequestBehavior.AllowGet);
33         }
34     }
35 }

result:

关于第三方插件,类型比较多,如Bootstrap-table等,希望广大读者朋友去研究。JqGrid,其功能很强大,在本篇文章中,仅仅是提及,下篇文章将重点分析JqGrid,与广大读者朋友分享。

2.6 ViewBag=》ViewData

2.7 ViewData=》ViewBag

2.8 ViewModel

留给读者朋友们去研究。。。。。。

2.9 Ajax+第三方插件(JqGrid,BootStrap-table)

留给读者朋友们去研究。。。。。。

3  View向Controller传递数据

3.1  QueryString

controller:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Mvc;
 6
 7 namespace MVCCrud.Areas.JqGridDemo.Controllers
 8 {
 9     public class QueryStringController : Controller
10     {
11         // GET: JqGridDemo/QueryString
12         public ActionResult Index()
13         {
14             return View();
15         }
16
17         public void GetParamsFromToView(string EmployeeID,string EmployeeName)
18         {
19             EmployeeID = Request["EmployeeID"].ToString();
20             EmployeeName= Request["EmployeeName"].ToString();
21         }
22     }
23 }

View:

 1 @{
 2     Layout = null;
 3 }
 4
 5 <!DOCTYPE html>
 6
 7 <html>
 8 <head>
 9     <meta name="viewport" content="width=device-width" />
10     <script src="~/OuterLibrary/Jquery/jquery-3.2.1.js"></script>
11     <title>Index</title>
12     <script>
13         $(function () {
14             $(‘#btnQueryString‘).click(function () {
15                 //url不区分大小写
16                 location.href ="/JqGridDemo/QueryString/GetParamsFromToView?EmployeeID=NX001&EmployeeName=张三";
17             });
18         });
19     </script>
20     <style>
21         #btnQueryString{
22             width:320px;
23             height:30px;
24         }
25     </style>
26
27 </head>
28 <body>
29     <div>
30         <button id="btnQueryString">QueryString向Controller传递值</button>
31     </div>
32 </body>
33 </html>

result:

3.2  AJax

controller:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Mvc;
 6
 7 namespace MVCCrud.Areas.JqGridDemo.Controllers
 8 {
 9     public class AjaxDataController : Controller
10     {
11         // GET: JqGridDemo/AjaxData
12         public ActionResult Index()
13         {
14             return View();
15         }
16
17         //action Receiving data from Ajax
18         public void GetParamsFromAjax(string EmployeeID, string EmployeeName)
19         {
20
21         }
22     }
23 }

View:

 1 @{
 2     Layout = null;
 3 }
 4
 5 <!DOCTYPE html>
 6
 7 <html>
 8 <head>
 9     <meta name="viewport" content="width=device-width" />
10     <script src="~/OuterLibrary/Jquery/jquery-3.2.1.js"></script>
11     <title>Index</title>
12     <script>
13         $(function () {
14             $(‘#btnAjax‘).click(function () {
15                 $.ajax({
16                     url: "/JqGridDemo/AjaxData/GetParamsFromAjax",
17                     type:"GET",
18                     data:{EmployeeID:‘NX001‘,EmployeeName:‘张三‘},
19                     error: function(message) {
20                         alert(‘error!‘);
21                     }
22                 });
23             })
24         })
25     </script>
26 </head>
27 <body>
28     <button id="btnAjax">Ajax传递参数</button>
29 </body>
30 </html>

或者

 1 @{
 2     Layout = null;
 3 }
 4
 5 <!DOCTYPE html>
 6
 7 <html>
 8 <head>
 9     <meta name="viewport" content="width=device-width" />
10     <script src="~/OuterLibrary/Jquery/jquery-3.2.1.js"></script>
11     <title>Index</title>
12     <script>
13         $(function () {
14             $(‘#btnAjax‘).click(function () {
15                 $.ajax({
16                     url: "/JqGridDemo/AjaxData/GetParamsFromAjax" +"?EmployeeID=‘NX001‘&EmployeeName=‘张三",
17                     type:"GET",
18                     //data:{EmployeeID:‘NX001‘,EmployeeName:‘张三‘},
19                     error: function(message) {
20                         alert(‘error!‘);
21                     }
22                 });
23             })
24         })
25     </script>
26 </head>
27 <body>
28     <button id="btnAjax">Ajax传递参数</button>
29 </body>
30 </html>

result:

3.3  Form传递

controller:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Mvc;
 6
 7 namespace MVCCrud.Areas.JqGridDemo.Controllers
 8 {
 9     public class FormTransferDataController : Controller
10     {
11         // GET: JqGridDemo/FormTransferData
12         public ActionResult Index()
13         {
14             return View();
15         }
16
17         //action Receiving data from Form
18         public void GetParamsFromForm(string EmployeeID, string EmployeeName)
19         {
20
21         }
22     }
23 }

View:

 1 @{
 2     Layout = null;
 3 }
 4
 5 <!DOCTYPE html>
 6
 7 <html>
 8 <head>
 9     <meta name="viewport" content="width=device-width" />
10     <title>Index</title>
11 </head>
12 <body>
13     <form action="/JqGridDemo/FormTransferData/GetParamsFromForm" method="get">
14         员工ID:<input type="text" name="EmployeeID" />
15         员工姓名:<input type="text" name="EmployeeName" />
16         <input type="submit" name="btnFormTransferData" value="Form表单传递数据" />
17     </form>
18 </body>
19 </html>

result:

3.4  FormCollection

controller:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Mvc;
 6
 7 namespace MVCCrud.Areas.JqGridDemo.Controllers
 8 {
 9     public class FormCollectionTransferDataController : Controller
10     {
11         // GET: JqGridDemo/FormCollectionTransferData
12         public ActionResult Index()
13         {
14             return View();
15         }
16
17         //action Receiving data from FormCollection
18         public void GetParamsFromFormCollection(FormCollection fc)
19         {
20             string EmployeeID = fc["EmployeeID"].ToString();
21             string EmployeeName = fc["EmployeeName"].ToString();
22         }
23     }
24 }

view:

 1 @{
 2     Layout = null;
 3 }
 4
 5 <!DOCTYPE html>
 6
 7 <html>
 8 <head>
 9     <meta name="viewport" content="width=device-width" />
10     <title>Index</title>
11 </head>
12 <body>
13     <div>
14         @using (Html.BeginForm("GetParamsFromFormCollection", "FormCollectionTransferData"))
15         {
16             @Html.TextBox("EmployeeID","员工ID");
17             @Html.TextBox("EmployeeName","员工姓名");
18             <input type="submit" value="FormCollection传值"/>
19         }
20     </div>
21 </body>
22 </html>

result:

3.5 自定义模型绑定

敬请期待,下篇文章与大家一起分享。。。。

4   版权

  • 感谢您的阅读,若有不足之处,欢迎指教,共同学习、共同进步。
  • 博主网址:http://www.cnblogs.com/wangjiming/。
  • 极少部分文章利用读书、参考、引用、抄袭、复制和粘贴等多种方式整合而成的,大部分为原创。
  • 如您喜欢,麻烦推荐一下;如您有新想法,欢迎提出,邮箱:[email protected]。
  • 可以转载该博客,但必须著名博客来源。
时间: 2024-12-26 04:19:13

【ASP.NET MVC】View与Controller之间传递数据的相关文章

mvc如何使用JavaScript在view和controller之间传递数据

在一般的BS项目开发中,我们经常需要在前台和后台之间传递数据,mvc架构中,也需要在view和controller之间传递数据,那么我们应该如何实现呢? view想controller传递数据:view中代码 <li>@Html.ViewComponent().WfSaveLink(Model).Id("saveToLink").OnBeforeDo("externalData")</li> <scriptlanguage="

【MVC架构】——怎样利用Json在View和Controller之间传递数据

在MVC架构中,尽管非常多东西和三层非常相似,可是也有非常大的差别.就比方传递数据.在三层架构中,传递数据就仅仅要一层返回,另外一层用同样类型的变量来接收即可了.在MVC中,事实上原理是一样的,Controller中的方法返回Json字符串.然后View来接收.或者反过来,不同的就是这之间须要一个序列化和反序列化的过程. 本文就简介利用Json在View和Controller之间传递数据的一个方面,大致从双方面介绍,一是什么是Json,二是怎样实现. 什么是Json 一.概念 百度百科说:JSO

MVC进阶学习--View和Controller之间的数据传递(一)

1.使用ViewData ViewData 的是ControllerBase 的一个属性,是一个数据字典类型的,其实现代码如(这段代码来自asp.net MVC开源项目中源码)下: Code  1 public class ViewDataDictionary : IDictionary<string, object> {  2   3         private readonly Dictionary<string, object> _innerDictionary = ne

ASP.NET MVC View向Controller提交数据

我们知道使用MVC的一个很重的的用途就是把Controller和View之间进行解耦,通过控制器来调用不同的视图,这就注定了Controller和View之间的传值是一个很重的知识点,这篇博文主要解释一下View向Controller提交数据的几种形式,认识有限,有不足的地方请各位博友能够给完善. 一.通过Json数据 方法一:使用$.getJSON //方式一:根据页码 异步请求 数据 function loadPageList(pageIndex) { $.getJSON("/Stu/Lis

MVC进阶学习--View和Controller之间的数据传递(二)

1. 使用Request.Form MVC 将页面简单化,与WebForm中的事件机制完全不同,就和普通的html标签表单提交没有任何区别(当然WebForm中的事件机制其实也是表单提交).在表单提交之后,在Controller action中可以以Request.Form["key"] 的方式获取到值. Code1 <%Html.BeginForm("Index", "Home", FormMethod.Post); %>2   &

ASP.NET MVC view与controller传值方式

1: ViewData传值方式ViewData的生命周期和View相同, 只对当前View有效.   ViewData["zd"] = dfdfd2:TempData传值方式   可以跨Action传递   TempData的数据至多只能经过一次Controller传递, 并且每个元素至多只能被访问一次,     例如一个用法为,抛出一个异常.跳转到error页面public ActionResult Index3(){      TempData["tempIndex&qu

ASP.NET MVC中 在controller 里将 Partial View 转化为字符串的方法

namespace Common.Helper { public static class ControllerExtension { //根据部分视图名称,把部分视图内容转换成字符串 public static string RenderPartialViewToString(this Controller controller, string partialViewName) { return controller.RenderPartialViewToString(partialViewN

ASP.Net MVC View

ASP.Net MVC View(视图) View视图职责是向用户提供界面.负责根据提供的模型数据,生成准备提供给用户的格式界面. 支持多种视图引擎(Razor和ASPX视图引擎是官方默认给出的,其实还支持其它N种视图引擎,甚至你自己都可以写一套视图引擎) View和Action之间数据传递(前后台数据传递) 弱类型 ViewData[""] 动态型 ViewBag //dynamic 动态类型Model             后台:return View(data); //存入 V

白话ASP.NET MVC之三:Controller是如何解析出来的

我们在上一篇文章中介绍Controller激活系统中所涉及到的一些类型,比如有关Controller类型的相关定义类型就包括了IController类型,IAsyncController类型,ControllerBase抽象类型和我们最终要使用的抽象类型Controller,这是ASP.NET MVC 框架中和Controller本身定义相关的类型.其他辅助类型,包括管理Controller的类型ControllerFactory,这个工厂负责Controller的生产和销毁.我们还涉及到另一个