ASP.NET MVC3中Controller與View之間的數(shù)據(jù)傳遞總結(jié)
來源:程序員人生 發(fā)布時(shí)間:2015-01-12 08:26:05 閱讀次數(shù):4798次
在ASP.NET MVC中,常常會(huì)在Controller與View之間傳遞數(shù)據(jù),因此,熟練、靈活的掌握這兩層之間的數(shù)據(jù)傳遞方法就非常重要。本文從兩個(gè)方面進(jìn)行探討:
1、 Controller向View傳遞數(shù)據(jù)
1. 使用ViewData傳遞數(shù)據(jù)
我們?cè)贑ontroller中定義以下:
ViewData[“Message_ViewData”] = “ Hello ViewData!”;
然后在View中讀取Controller中定義的ViewData數(shù)據(jù),代碼以下:
@Html.Encode(ViewData["Message_ViewData"])
js中讀取ViewData中數(shù)據(jù)以下:
<pre name="code" class="javascript"><script type="text/javascript">
var viewData = '@ViewData["Message_ViewData"]';
</script>
2. 使用ViewBag傳遞數(shù)據(jù)
我們?cè)贑ontroller中定義以下:
ViewBag.Message_ViewBag = “ Hello ViewBag !”;
然后在View中讀取Controller中定義的ViewBag數(shù)據(jù),代碼以下:
@Html.Encode(ViewBag.Message_ViewBag)
js中讀取ViewBag中數(shù)據(jù)以下:
<script type="text/javascript">
var viewBag= '@ViewBag.Message_ViewBag';
</script>
3. 使用TempData傳遞數(shù)據(jù)
我們?cè)贑ontroller中定義以下:
TempData[“Message”] = “Hello word!”;
然后在View中讀取Controller中定義的TempData數(shù)據(jù),代碼以下:
@Html.Encode(TempData["Message_TempData"])
js中讀取TempData中數(shù)據(jù)以下:
<script type="text/javascript">
var tempData = '@TempData["Message"]';
</script>
4. 使用Model傳遞數(shù)據(jù)
首先要?jiǎng)?chuàng)建Model實(shí)體類:
public class HelloModel
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
private string _text;
public string Text
{
get { return _text; }
set { _text = value; }
}
}
使用Model傳遞數(shù)據(jù)的時(shí)候,通常在創(chuàng)建View的時(shí)候我們會(huì)選擇創(chuàng)建強(qiáng)類型View以下圖所示:

模型類下拉列表框當(dāng)選中剛才創(chuàng)建的HelloModel
創(chuàng)建強(qiáng)類型的View以后,View的第1行代碼以下所示:
@model Test.Models.HelloModel
就代表了這個(gè)View使用的Model為“Test.Models.HelloModel”
然后在View中讀取Model中定義的數(shù)據(jù),代碼以下:
@Html.Encode(Model.Name)
js中讀取Model中數(shù)據(jù)以下:
<script type="text/javascript">
var modelName = '@Model.Name';
</script>
總結(jié):
1. ViewData與TempData方式是弱類型的方式傳遞數(shù)據(jù),而使用Model傳遞數(shù)據(jù)是強(qiáng)類型的方式。
2. ViewData與TempData是完全不同的數(shù)據(jù)類型,ViewData數(shù)據(jù)類型是ViewDataDictionary類的實(shí)例化對(duì)象,而TempData的數(shù)據(jù)類型是TempDataDictionary類的實(shí)例化對(duì)象。
3. TempData實(shí)際上保存在Session中,控制器每次履行要求時(shí)都會(huì)從Session中獲得TempData數(shù)據(jù)并刪除該Session。TempData數(shù)據(jù)只能在控制器中傳遞1次,其中的每一個(gè)元素也只能被訪問1次,訪問以后會(huì)被自動(dòng)刪除。
4. ViewData只能在1個(gè)Action方法中進(jìn)行設(shè)置,在相干的視圖頁(yè)面讀取,只對(duì)當(dāng)前視圖有效。理論上,TempData應(yīng)當(dāng)可以在1個(gè)Action中設(shè)置,多個(gè)頁(yè)面讀取。但是,實(shí)際上TempData中的元素被訪問1次以后就會(huì)被刪除。
5. 在MVC3開始,視圖數(shù)據(jù)可以通過ViewBag屬性訪問,在MVC2中則是使用ViewData。MVC3中保存了ViewData的使用,有關(guān)他們之間的區(qū)分可以參考這個(gè)文章。
MVC3中 ViewBag、ViewData和TempData的使用和區(qū)分
2、 View向Controller傳遞數(shù)據(jù)
在ASP.NET MVC中,將View中的數(shù)據(jù)傳遞到控制器中,主要通過發(fā)送表單的方式來實(shí)現(xiàn)。具體的方式有:
1. 通過Request.Form讀取表單數(shù)據(jù)
我們?cè)赩iew層做以下定義:
@using (Html.BeginForm("HelloModelTest", "Home", FormMethod.Post))
{
@Html.TextBox("Name");
@Html.TextBox("Text");
<input type="submit" value="提交" />
}
注意:
HelloModelTest為對(duì)應(yīng)的Action名,Home為對(duì)應(yīng)的Controller名稱
然后在Controller層,通過Request.Form讀取表單數(shù)據(jù)的代碼以下所示:
[HttpPost]
public ActionResult HelloModelTest()
{
string name= Request.Form["Name"];
string text= Request.Form["Text"];
return View();
}
2. 通過FormCollection讀取表單數(shù)據(jù)
我們?cè)赩iew層做以下定義:
@using (Html.BeginForm("HelloModelTest", "Home", FormMethod.Post))
{
@Html.TextBox("Name");
@Html.TextBox("Text");
<input type="submit" value="提交" />
}
然后在Controller層,通過FormCollection讀取表單數(shù)據(jù)的代碼以下所示:
[HttpPost]
public ActionResult HelloModelTest(FormCollection fc)
{
string name= fc["Name"];
string text = fc["Text"];
return View();
}
3. 模型綁定
我們?cè)赩iew層做以下定義:
@using (Html.BeginForm("HelloModelTest", "Home", FormMethod.Post))
{
@Html.TextBox("Name");
@Html.TextBox("Text");
<input type="submit" value="提交" />
}
默許的模型綁定
相較于從要求中獲得表單值,下面的Edit Action則是簡(jiǎn)單地以1個(gè)模型對(duì)像為參數(shù)(Album):
[HttpPost]
public ActionResult HelloModelTest( HelloModel model)
{
// ...
}
當(dāng)你的Action方法是以1個(gè)模型對(duì)象充當(dāng)參數(shù)時(shí),MVC運(yùn)行時(shí)將會(huì)用模型綁定來構(gòu)建該參數(shù)。默許用于模型綁定的是 DefaultModelBinder,以上述的HelloModel為例,DefaultModelBinder將會(huì)檢索出所有可用的HelloModel屬性用于綁定模型。根據(jù)命名約定,DefaultModelBinder能夠自動(dòng)地在要求中獲得相應(yīng)的值來填充HelloModel對(duì)象(它還能創(chuàng)建1個(gè)對(duì)象的實(shí)例來填充)
換句話說,假定HelloModel有1個(gè)Name屬性,那末模型綁定就會(huì)在要求中查找名為Name的參數(shù)。注意我說的是在“要求中”,而不是“表單集合”中。模型綁定會(huì)在要求中的各個(gè)方面進(jìn)行值查找,這里面包括路由數(shù)據(jù),查詢字符串,表單集合。有必要的話你還可以添加自定義的值提供信息。
模型綁定不并局限于Http Post及復(fù)雜參數(shù)(如HelloModel),你完全可以傳入1個(gè)原始的簡(jiǎn)單參數(shù):
public ActionResult HelloModelTest( string name,string text)
{
// ….
}
在該場(chǎng)景中,模型綁定將會(huì)在要求中查找名為name,text 的參數(shù)。
顯式模型綁定
當(dāng)Action有參數(shù)的時(shí)候,會(huì)隱式地履行模型綁定。你還可以在控制器里面使用UpdateModel和 TryUpdateModel來顯式調(diào)用模型綁定。調(diào)用UpdateModel的時(shí)候,如果模型對(duì)象是無效的或綁定期間產(chǎn)生毛病則會(huì)拋出異常。TryUpdateModel則不會(huì)拋出異常,它返回1個(gè)布爾值:如果綁定成功并且模型驗(yàn)證通過則返回true,否則返回false。
[HttpPost]
public ActionResult HelloModelTest( )
{
HelloModel model = new HelloModel();
if (this.TryUpdateModel(model))
{
//綁定成功
}
else
{
//綁定失敗
}
}
模型狀態(tài)是模型綁定產(chǎn)生的副產(chǎn)物。每次綁定器綁定值到模型時(shí),都會(huì)在模型狀態(tài)中進(jìn)行記錄。你可以在模型綁定以后查看模型狀態(tài)來判斷綁定是不是成功:
[HttpPost]
public ActionResult HelloModelTest( )
{
HelloModel model = new HelloModel();
this.TryUpdateModel(model);
if (ModelState.IsValid)
{
//綁定成功
}
else
{
<pre code_snippet_id="569649" snippet_file_name="blog_20150102_21_3590846" name="code" class="csharp"><span style="white-space:pre"> </span>//綁定失敗
}}
如果在模型綁定進(jìn)程中產(chǎn)生異常,模型狀態(tài)里面就會(huì)包括致使異常的那個(gè)屬性名,綁定值和毛病信息。
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)