ASP.NET MVC 之控制器与视图之间的数据传递

时间:2022-10-20 06:23:38

今天,我们来谈谈控制器与视图之间的数据传递。

数据传递,指的是视图与控制器之间的交互,包括两个方向上的数据交互,一个是把控制器的数据传到视图中,在视图中如何显示数据,一个是把视图数据传递到控制器中,

如何在控制器中获取,处理这些数据。

ASP.NET MVC 中所有控制器都继承Controller类,而Controller又继承自ControllerBase,而ControllerBase下又包含ViewData以及TempData视图数据字典。

一,使用ViewData传递数据

ViewData 只在当前 Action 中有效,生命周期和 View 相同,属于弱类型数据。用法与C#中字典用法相似,以键值对的方式进行存储。

ViewData可以存储任何数据类型,如类,DataTable,DataSet,json等。

用法举例:

public ActionResult Index()
{
ViewData["mydata"] = "index";
return View();
}

前台代码:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<!DOCTYPE html>

<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<%=ViewData["mydata"] %> </div>
</body>
</html>

二,使用TempData传递数据

TempData与ViewData类似,以键值对的方式进行存储,保存在Session之中,进行一次读取之后Session就会消失,变为null。看下面代码:

 public ActionResult Index()
{ //AVON.DMS.DAL.Entities DMS = new AVON.DMS.DAL.Entities();
//AVON.DMS.Model.REP A = DMS.REP.SingleOrDefault<AVON.DMS.Model.REP>(t => t.NO == "00561874");
//AVON.DMS.BLL.Rep repBLL = new AVON.DMS.BLL.Rep();
//AVON.DMS.Model.REP A = repBLL.GetFromRep("00561874");
//ViewData["mydata"] = A.JOINDATE;
ViewData["mydata"] = "index";
TempData["mytemp"] = "huihui";
return View();
}

前端代码:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<!DOCTYPE html>

<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<%=ViewData["mydata"] %>
<%--<%=TempData["mytemp"] %>--%>
<a href="add">跳转到下一页</a>
</div>
</body>
</html>

在浏览器输入地址,http://localhost:7449/dms/index,显示如下:

ASP.NET MVC 之控制器与视图之间的数据传递

点击"跳转到下一页",进入http://localhost:7449/dms/add,显示如下:

ASP.NET MVC 之控制器与视图之间的数据传递

我们看看add这个Action的代码:

 public ActionResult Add()
{ ViewData["mydata"] = TempData["mytemp"];
//Session.Remove("temp");
return View();
}

前端:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<!DOCTYPE html>

<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>Add</title>
</head>
<body>
<div>
add
<%=ViewData["mydata"] %>
<a href="index">跳转到上一页</a>
</div>
</body>
</html>

可见,add获取到了TempData["mytemp"]的值。我们尝试刷新一下http://localhost:7449/dms/add,显示如下:

ASP.NET MVC 之控制器与视图之间的数据传递

ViewData["mttemp"]的值已经变为null,所以,可以看出TempData的值一旦读取,就会失效。需重新赋值。

三,使用Model传递数据

ViewData与TempData都是弱类型数据,那么如果我们想传递强类型数据,应该怎样编写代码呢?代码如下:

public ActionResult Detail()
{
DRMModel.Dealer dealer = new DRMModel.Dealer();
dealer.RecruiterID = "";
dealer.Recruiter = "";
dealer.NationalID = "";
dealer.dealer_name = "dsdsds";
dealer.sex = "";
dealer.BirthYear = "";
dealer.BirthMonth = "";
dealer.BirthDay = "";
var Model = dealer;
return View(Model);
}

右击detail方法,添加视图,勾选 Create a strongly-typed view,如下图:

ASP.NET MVC 之控制器与视图之间的数据传递

点击添加之后,编写如下代码:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<DRMModel.Dealer>" %>

<!DOCTYPE html>

<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>Detail</title>
</head>
<body>
<div>
<%=Model.dealer_name %>
</div>
</body>
</html>

在浏览器输入地址:http://localhost:55706/home/detail,显示如下:

ASP.NET MVC 之控制器与视图之间的数据传递

当然,你也可以编写更为复杂的类,传递多个数据对象进行数据绑定。如下图:

 public ActionResult Bind()
{
DRMModel.NewDealer newDealer = new DRMModel.NewDealer();
DRMModel.Dealer dealer = new DRMModel.Dealer();
dealer.RecruiterID = "";
dealer.Recruiter = "";
dealer.NationalID = "";
dealer.dealer_name = "dsdsds";
dealer.sex = "";
dealer.BirthYear = "";
dealer.BirthMonth = "";
dealer.BirthDay = "";
DRMModel.Contact contact = new DRMModel.Contact();
DRMModel.HouseAddress ha = new DRMModel.HouseAddress();
DRMModel.RDaddress rd = new DRMModel.RDaddress();
DRMModel.SendAddress sa = new DRMModel.SendAddress();
newDealer.Contact = contact;
newDealer.HouseAddress = ha;
newDealer.RDaddress = rd;
newDealer.SendAddress = sa;
newDealer.Dealer = dealer;
var Model = newDealer;
return View(Model);
}

以上都是谈了控制器往视图传递数据,那么,控制器怎么获取视图提交的数据呢?今天,我们只介绍获取Post方式传送数据的方法。

假设,表单通过Post方式提交了,下列数据:RecruiterID = "1";Recruiter = "2";NationalID = "2";dealer_name = "dsdsds";

看以下方法代码:

/// <summary>
/// 处理表单提交数据,方法1:使用传统的Request请求取值
/// </summary>
/// <returns></returns>
[HttpPost]
public ActionResult AcceptFrom()
{
ViewData["RecruiterID"] = Request.Form["RecruiterID"];
ViewData["Recruiter"] = Request.Form["Recruiter"];
ViewData["NationalID"] = Request.Form["NationalID"];
ViewData["dealer_name"] = Request.Form["dealer_name"];
return View();
} /// <summary>
/// 处理表单提交数据,方法2:Action参数名与表单元素name值一一对应
/// </summary>
/// <param name="RecruiterID"></param>
/// <param name="Recruiter"></param>
/// <param name="NationalID"></param>
/// <param name="dealer_name"></param>
/// <returns></returns>
[HttpPost]
public ActionResult AcceptbyPara(string RecruiterID, string Recruiter, string NationalID, string dealer_name)
{
ViewData["RecruiterID"] = RecruiterID;
ViewData["Recruiter"] = Recruiter;
ViewData["NationalID"] = NationalID;
ViewData["dealer_name"] = dealer_name;
return View();
} /// <summary>
/// 处理表单提交数据,方法3:从MVC封装的FormCollection容器中读取
/// </summary>
/// <param name="form"></param>
/// <returns></returns>
[HttpPost]
public ActionResult AcceptCollection(FormCollection form)
{
ViewData["RecruiterID"] = form["RecruiterID"];
ViewData["Recruiter"] = form["Recruiter"];
ViewData["NationalID"] = form["NationalID"];
ViewData["dealer_name"] = form["dealer_name"];
return View();
} /// <summary>
/// 处理表单提交数据,方法4:使用实体作为Action参数传入,前提是提交的表单元素名称与实体属性名称一一对应
/// </summary>
/// <param name="dealer"></param>
/// <returns></returns>
[HttpPost]
public ActionResult AcceptbyModel(DRMModel.Dealer dealer)
{
ViewData["RecruiterID"] = dealer.RecruiterID;
ViewData["Recruiter"] = dealer.Recruiter;
ViewData["NationalID"] = dealer.NationalID;
ViewData["dealer_name"] = dealer.dealer_name;
return View();
}

假如。我们要传json数据呢,又应该怎么处理呢?看以下的例子:

我在HomeController 下的Index方法添加如下代码,模拟Post提交json数据。

 public ActionResult Index()
{ DRMModel.NewDealer newDealer = new DRMModel.NewDealer();
DRMModel.Dealer dealer = new DRMModel.Dealer();
dealer.RecruiterID = "";
dealer.Recruiter = "";
dealer.NationalID = "";
dealer.dealer_name = "dsdsds";
dealer.sex = "";
dealer.BirthYear = "";
dealer.BirthMonth = "";
dealer.BirthDay = "";
DRMModel.Contact contact = new DRMModel.Contact();
DRMModel.HouseAddress ha = new DRMModel.HouseAddress();
DRMModel.RDaddress rd = new DRMModel.RDaddress();
DRMModel.SendAddress sa = new DRMModel.SendAddress();
newDealer.Contact = contact;
newDealer.HouseAddress = ha;
newDealer.RDaddress = rd;
newDealer.SendAddress = sa;
newDealer.Dealer = dealer;
JavaScriptSerializer json = new JavaScriptSerializer();
string postdata = json.Serialize(newDealer);
//postdata = "RecruiterID=1&Recruiter=2&NationalID=1&dealer_name=fafaf&sex=1&BirthYear=1989&BirthMonth=09&BirthDay=01";
string pageHtml = "";
//var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://avondms.avon.com.tw/DMS/DMSApi/api/Newdealer/add");
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:55706/home/add");
//httpWebRequest.ContentType = "text/json";
//httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{ streamWriter.Write(postdata);
streamWriter.Flush();
streamWriter.Close();
} var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
pageHtml = streamReader.ReadToEnd();
} ViewData["pram1"] = pageHtml; return View();
}

在HomeController add方法添加如下代码:

   [HttpPost]
public string add(DRMModel.NewDealer newDealer)
{
//string rtn = Request.Form["dealer_name"];
string rtn = newDealer.Dealer.dealer_name;
return rtn;
}

在浏览器中输入地址:http://localhost:55706/home/index,显示如下:

ASP.NET MVC 之控制器与视图之间的数据传递

由此可见,ASP.NET MVC 可把json数据转化为C#中的强类型数据,只要数据一一对应。

好了,今天写到这里,希望对您有所帮助,O(∩_∩)O哈哈~