ViewBag
在MVC3開始。视图数据能够通过ViewBag属性訪问。在MVC2中则是使用ViewData。MVC3中保留了ViewData的使用。ViewBag 是动态类型(dynamic),ViewData 是一个字典型的(Dictionary)。
ViewBag和ViewData的差别:
ViewBag 不再是字典的键值对结构。而是 dynamic 动态类型。它会在程序执行的时候动态解析。
所以在视图中获取它的数据时候不须要进行类型转换
ViewData | ViewBag |
它是Key/Value字典集合 | 它是dynamic类型对像 |
从Asp.net MVC 1 就有了 | ASP.NET MVC3 才有 |
基于Asp.net 3.5 framework | 基于Asp.net 4.0与.net framework |
ViewData比ViewBag快 | ViewBag比ViewData慢 |
在ViewPage中查询数据时须要转换合适的类型 | 在ViewPage中查询数据时不须要类型转换 |
有一些类型转换代码 | 可读性更好 |
Contorller
<pre class="csharp" name="code">using NewOjbect.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace NewOjbect.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.UserName = "无盐海";
ViewBag.Age = "25";
ViewBag.Gender = 1;
string[] Itmes = new string[] { "中国", "美国", "德国" };
ViewBag.itemsA = Itmes;// viewbag是一个新的dynamic类型keyword的封装器 //ViewData["Items"] = items;
return View();
}
}
}
View
<pre class="html" name="code"><html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Test2</title>
</head>
<body>
<div>
username:<input type="text" id="UserName" name="UserName" value="@ViewBag.UserName" /></br>
年 龄: <input type="text" id="age" name="age" value=@ViewBag.Age /></br>
性 别:<input type="text" id="Gender" name="Gender" value="@ViewBag.Gender" /></br>
<button>提交</button>
<!---这里输出国家名-->>
@foreach (dynamic item in ViewBag.itemsA)
{
<p>@item</p>
}
</div>
</body>
</html>
出处:https://www.cnblogs.com/cynchanpin/p/7065098.html
ViewBag+Hashtable应用例子
ViewBag+Hashtable应用例子
ViewBag+Hashtable应用例子
1.Controller返回Hashtable 数据
public ActionResult Index()
{
ViewBag.Qual = getQual();//返回ViewBag用Hashtable格式
return View();
}
public Hashtable getQual()
{
var sql = "select Qualification, Qualification_url from C_Qualification";
var Qual_dt = DbHelperSQL.Query(sql);//查询数据后返回datatable数据
Hashtable hash = new Hashtable();//new一个Hashtable对象
for (int i = 0; i < Qual_dt.Rows.Count; i++)
//根据datatable数据行数遍历再添加到Hashtable以键值对形式存在:::key:value
{
hash.Add(Qual_dt.Rows[i][0].ToString(), Qual_dt.Rows[i][1].ToString());
}
return hash;
}
2.前端显示及Hashtable 数据foreach遍历
<div class="layui-tab-item">
<table class="layui-table">
<colgroup>
<col width="150">
<col width="200">
<col>
</colgroup>
<thead>
<tr>
<th>资质名称</th>
<th>预览</th>
</tr>
</thead>
<tbody>
@{
foreach (var item in ViewBag.Qual)
{
<tr>
<td>@item.Key</td>
<td>@item.Value</td>
</tr>
}
}
</tbody>
</table>
</div>