MVC_ViewBag(Method)
MVC_ViewBag(Method)
1. ViewBag v.s ViewData (View)
//ViewData
@foreach(var item in ViewData["CustomerList"]) as List<OrderDetails>
{
OrderID: @item.OrderID, ProductID: @item.ProductID,....
}
//ViewBag
@foreach(var item in ViewBag.CustomerList)
{
OrderID: @item.OrderID, ProductID: @item.ProductID,....
}
2.ViewBag use Method
利用Func的委派特性,將Method放入ViewBag中,在View頁面中,將相關資料指定給ViewBag,即可處理( => 將邏輯寫置Controller中)
Controller
public ActionResult index(){
using(testEntities db = new testEntities()){
var model =....
.....
.....
.....
ViewBag.DetermineTotalPrice = new Func<decimal, string>(DetermineTotalPrice);
//Func<T, TResult> 委派
//public delegate TResult Func<in T, out TResult>(T arg )
//in T 這個委派所封裝之方法的參數類型。
//out TResult 這個委派所封裝之方法的傳回值之類型。
//T arg 這個委派所封裝之方法的參數。
return View(Model);
}
}
Function
// DetermineTotalPrice
private string DetermineTotalPrice (decimal totalPrice)
{
if (totalPrice >= 500 && totalPrice < 1000)
{
....
return string
}
else if (...)
{
...
return string
}
.......
.......
return string
}
View
@foreach(var item in model)
{
<tr>
<td>
@item.CustomerID
</td>
<td>
@HTML.Raw(ViewBag.DetermineTotalPrice(item.TotalPrice)) //TotalPrice => decimal
</td>
</tr>
}
參考網址:http://kevintsengtw.blogspot.com/2012/04/aspnet-mvc-3viewbag-method.html