Controller傳資料給View的四種方式 | Return View 參數
Controller傳資料給View的四種方式 1.ViewDataKey與Value成對的Dictionary,不能跨Controller/Action//Controller內設定ViewDataViewData["Key"]=Value//View內存取ViewData@ViewData["Key"]@((int)ViewData["Key"]+1)//除了字串外,提取資料需要明確轉型2.ViewBagDynamic動態型別,不能跨Controller/Action//Controller內設定ViewBagViewBag.name=Value//View內設定[email protected]//不需轉型3.Model廣義資料模型,如集合、陣列或物件都可作為Model傳給View,不能跨Controller/Action//呼叫View方法,直接將model...
Controller傳資料給View的四種方式
1.ViewData
Key與Value成對的Dictionary,不能跨Controller/Action
//Controller內設定ViewData
ViewData["Key"]=Value
//View內存取ViewData
@ViewData["Key"]
@((int)ViewData["Key"]+1)//除了字串外,提取資料需要明確轉型
2.ViewBag
Dynamic動態型別,不能跨Controller/Action
//Controller內設定ViewBag
ViewBag.name=Value
//View內設定ViewBag
@ViewBag.name //不需轉型
3.Model
廣義資料模型,如集合、陣列或物件都可作為Model傳給View,不能跨Controller/Action
//呼叫View方法,直接將model當成參數傳入
return View(model物件) //建議使用此方式
//將model物件指定給ViewData.Model屬性
ViewData.Model=model物件
return View()
4.TempData
Key與Value成對的Dictionary,資料儲存在Session可以跨Controller/Action
//Controller內設定TempData
TempData["Key"]=Value
//View內存取TempData
@TempData["Key"] //除了string之外的資料需要做轉型
...