Razor Pages use TempData.
ViewBag in asp.net core
Do you know how to activate ViewBag in PageModel (x.cshtml.cs files) of asp.net core 3.1? Thanks
4 answers
Sort by: Most helpful
-
-
Michael Taylor 54,316 Reputation points
2022-04-01T15:29:49.287+00:00 You do not have access to
ViewBag
insidePageModel
. There are hacks to get it to work but there is no reason to do so.To store data temporarily you must use
TempData
orViewData
. If you need access to the data in the view then useViewData
instead ofViewBag
.public class Index: PageModel { //Preferred approach [ViewData] public KeyValuPair<string, string>[] Values { get; set; } public void OnGet () { //Only if really, really needed ViewData["Values"] = kvpArray; } } @page @{ var kvp = ViewData["Values"] as KeyValuePair<string, string>[]; }
I should point out that an array of
KeyValuePair
is really just a dictionary so if you simply useDictionary<K,V>
your code would be easier to work with I believe. -
Zhi Lv - MSFT 32,326 Reputation points Microsoft Vendor
2022-04-04T05:27:05.247+00:00 Hi @S A ,
ViewBag is a wrapper around the ViewData dictionary and provides an alternative way to access ViewData contents within ASP.NET Core MVC controllers using dynamic properties instead of string-based indexes. A design decision was made NOT to include a ViewBag property in the Razor Pages PageModel class, but you can use ViewBag to reference ViewData entries from within a Razor content page or layout page:
Like this:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.Best regards,
Dillion -
S A 86 Reputation points
2022-04-07T14:34:10.677+00:00 Thank you very much for everyone.