ASP.NET MVC 之控制器與視圖之間的數據傳遞

今天,咱們來談談控制器與視圖之間的數據傳遞。html

數據傳遞,指的是視圖與控制器之間的交互,包括兩個方向上的數據交互,一個是把控制器的數據傳到視圖中,在視圖中如何顯示數據,一個是把視圖數據傳遞到控制器中,前端

如何在控制器中獲取,處理這些數據。json

ASP.NET MVC 中全部控制器都繼承Controller類,而Controller又繼承自ControllerBase,而ControllerBase下又包含ViewData以及TempData視圖數據字典。api

 一,使用ViewData傳遞數據瀏覽器

ViewData 只在當前 Action 中有效,生命週期和 View 相同,屬於弱類型數據。用法與C#中字典用法類似,以鍵值對的方式進行存儲。app

ViewData能夠存儲任何數據類型,如類,DataTable,DataSet,json等。post

用法舉例:ui

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

前臺代碼:url

<%@ 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傳遞數據spa

 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,顯示以下:

點擊"跳轉到下一頁",進入http://localhost:7449/dms/add,顯示以下:

 

咱們看看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,顯示以下:

ViewData["mttemp"]的值已經變爲null,因此,能夠看出TempData的值一旦讀取,就會失效。需從新賦值。

三,使用Model傳遞數據

 ViewData與TempData都是弱類型數據,那麼若是咱們想傳遞強類型數據,應該怎樣編寫代碼呢?代碼以下:

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

右擊detail方法,添加視圖,勾選 Create a strongly-typed view,以下圖:

點擊添加以後,編寫以下代碼:

<%@ 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,顯示以下:

固然,你也能夠編寫更爲複雜的類,傳遞多個數據對象進行數據綁定。以下圖:

 public ActionResult Bind()
        {
            DRMModel.NewDealer newDealer = new DRMModel.NewDealer();
            DRMModel.Dealer dealer = new DRMModel.Dealer();
            dealer.RecruiterID = "1";
            dealer.Recruiter = "2";
            dealer.NationalID = "2";
            dealer.dealer_name = "dsdsds";
            dealer.sex = "1";
            dealer.BirthYear = "1989";
            dealer.BirthMonth = "09";
            dealer.BirthDay = "01";
            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 = "1";
            dealer.Recruiter = "2";
            dealer.NationalID = "2";
            dealer.dealer_name = "dsdsds";
            dealer.sex = "1";
            dealer.BirthYear = "1989";
            dealer.BirthMonth = "09";
            dealer.BirthDay = "01";
            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 可把json數據轉化爲C#中的強類型數據,只要數據一一對應。

 

好了,今天寫到這裏,但願對您有所幫助,O(∩_∩)O哈哈~

相關文章
相關標籤/搜索