Controller向View傳值方式

2022-02-01 19:19:31 字數 1833 閱讀 9986

我們一般會向頁面傳遞乙個主要的型別的資料,一般情況下是乙個list

viewbag  viewdata  tempdata之間的差別

viewdata與viewbag之間非常相似,二者使用場景基本一致,但是viewdata的型別時很明確的,而viewbag的型別時動態的,直接就可以使用,他們的傳值範圍是:controller向view傳值,view自己和自己傳值。而tempdata存在的目的就是為了防止redirect的時候資料丟失,所以他的傳值範圍就是當前controller和跳轉後的controller之間。

具體用法:

viewbag:

1.controller向view傳值

view:

@viewbag.message

controller:

public actionresult index()

2.view向view傳值(同乙個view之間傳值)

@@viewbag.title

3.viewbag傳遞乙個物件

view:

controller:

public actionresult index()

;viewbag.students = students;

return view();

}viewdata:

1.viewdata基本用法

view:

controller:

public actionresult index()

;viewdata["students"] = students;

return view();

}viewdata轉換成viewbag:

view:

controller:

public actionresult index()

;viewdata["students"] = students;

return view();

}viewbag轉換成viewdata:

view:

controller:

public actionresult index()

viewbag.students = students;

return view();

}tempdata:

tempdata用於在redirect的時候儲存資料,而viewdata和viewbag在跳轉後就會變成null

public actionresult index()

;tempdata["modelname"] = model;

return redirecttoaction("about");

}public actionresult about()

普通頁面傳遞model:

controller:

public actionresult index()

view:

product : <%: ((product)model).name %>

向強型別檢視傳遞model:

controller:

public actionresult index()

view:

宣告型別

<%@ page inherits="system.web.mvc.viewpage" %>

直接用model呼叫該物件

razor檢視引擎:

在razor中呼叫物件的方式:

Controller向View傳遞資料

1.使用viewdata傳遞資料 我們在controller中定義如下 viewdata message hello word 然後在view中讀取controller中定義的viewdata資料,如下 2.使用tempdata傳遞資料 我們在controller中定義如下 tempdata mes...

如何通過View獲取Controller

我們知道,對於乙個檢視控制器類uiviewcontroller,可以通過 self view 來獲取到它所管理的檢視uiview,反過來,對於乙個檢視類uiview,我們怎麼獲取到它的uiviewcontroller?uiview繼承自uiresponder,uiresponder有乙個例項方法 u...

如何呼叫父view的controller裡面的方法

答案如下 self superview nextresponder method self superview nextresponder method self.nextresponder method 上面的都可以,看情況使用,使用的時候最好判斷一下。即如下 可以進行判斷 id next sel...