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

      2020-08-02 17:07      HTML5

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

CustomerInfo 2 {EmployeeID { get; set; }EmployeeName { get; set; }EmployeeMajor { get; set; }EmployeeDepartment { get; set; }EmployeeTel { get; set; }EmployeeEmail { get; set; }EmployeeJiGuan { get; set; }EmployeeAddress { get; set; }EmployeePosition { get; set; }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][].ToString();custInfo.EmployeeName = dt.Rows[i][].ToString();custInfo.EmployeeMajor = dt.Rows[i][].ToString();custInfo.EmployeeDepartment = dt.Rows[i][].ToString();custInfo.EmployeeTel = dt.Rows[i][].ToString();custInfo.EmployeeEmail = dt.Rows[i][].ToString();custInfo.EmployeeJiGuan = dt.Rows[i][].ToString();custInfo.EmployeeAddress = dt.Rows[i][].ToString();custInfo.EmployeePosition = dt.Rows[i][].ToString();custInfo.EmployeeBirthday = dt.Rows[i][].ToString();ltPI.Add(custInfo);},ltPI);}

b.ADO.NET 获取CustomerInfo数据

DataTable GetCustomerInfoToDataTable() 3 {conStr = ConfigurationManager.ConnectionStrings[].ConnectionString;; 7using (SqlConnection conn = new SqlConnection(conStr)) 8 { 9 conn.Open();10SqlCommand cmd = new SqlCommand(strSql, conn);11 cmd.ExecuteNonQuery();12SqlDataAdapter sda = new SqlDataAdapter(strSql, conn);13DataSet ds = new DataSet(););];16 }17}

(4)View

1 @{ 2 Layout = null; 3 }Index员工ID员工姓名员工专业员工部门员工电话员工邮件员工籍贯员工住址员工职位员工生日@foreach (var item in Model)36 {@[email protected]@[email protected]@[email protected]@[email protected]@[email protected]}

(5)结果

2.2 ViewData传递数据

(1)DB表:

(2)Model

CustomerInfo 2 {EmployeeID { get; set; }EmployeeName { get; set; }EmployeeMajor { get; set; }EmployeeDepartment { get; set; }EmployeeTel { get; set; }EmployeeEmail { get; set; }EmployeeJiGuan { get; set; }EmployeeAddress { get; set; }EmployeePosition { get; set; }EmployeeBirthday { get; set; }13}

(3)Controller

a.控制器action