MVC5控制器传值的三种方式(ViewData,ViewBag,TempData),刚刚学习MVC5的新手,希望各位大神多多指教

mvc传值的三种方式:
1.ViewData 在使用过程中需要类型转换
例子:
ViewData["MyTitle"]="ViewData传值";
引用:
@ViewData["MyTitle"]
例子:
List<string> strs=new List<string>{"China","Apple","Pear"};
ViewData["jihe"]=strs;
引用:
@foreach(var item in ViewData["jihe"] as List<string>)
{
<li>
@item
</li>
}
例子:
Dictionary<int, string> strsa = new Dictionary<int, string>();
strsa.Add(1, "China");
strsa.Add(2, "Star");
strsa.Add(3, "NLJ");
ViewData["jihe1"] = strsa;
引用:
@foreach(var item in ViewData["jihe1"] as Dictionary<int,string>)
{
<li>
@item.Key:@item.Value
</li>
}
2.ViewBag 在使用过程中不需要类型转换
例子:ViewBag.asas="ViewBag传值";//变量名随便起,没有规定
引用:@ViewBag.asas
例子:Dictionary<int,string> strsa=new Dictionary<int,string>();
strsa.Add(2,"China");
strsa.Add(3,"Apple");
strsa.Add(4,"Pear");
ViewBag.jihe=strsa;
引用:@foreach(var item in ViewBag.jihe)
{
<li>
@item.Key:@item.Value
</li>
}
例子:
List<string> strs = new List<string> { "China", "Pear", "Apple" };
ViewBag.str1 = strs;
引用:
@foreach(var item in ViewBag.str1)
{
<li>
@item
</li>
}
3.TempData
例子:TempData["MyTem"]="TempData传值";
引用:@TempData["MyTem"]
例子:Dictionary<int,string> strsa=new Dictionary<int,string>();
strsa.Add(2,"China");
strsa.Add(3,"Apple");
strsa.Add(4,"Pear");
TempData["jihe"]=strsa;
引用:
@foreach(var item in TempData["jihe"] as Dictionary<int,string>)
{
<li>
@item.Key:@item.Value
</li>
}
例子:
List<string> strs=new List<string>{"China","Apple","Pear"};
TempData["jihe"]=strs;
引用:
@foreach(var item in TempData["jihe"] as List<string>)
{
<li>
@item
</li>
}

posted @ 2018-07-06 11:33 SAS、A 阅读(...) 评论(...) 编辑 收藏