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
Developer technologies | ASP.NET | ASP.NET Core
4 answers
Sort by: Most helpful
-
-
Michael Taylor 61,096 Reputation points
2022-04-01T15:29:49.287+00:00 You do not have access to
ViewBaginsidePageModel. There are hacks to get it to work but there is no reason to do so.To store data temporarily you must use
TempDataorViewData. If you need access to the data in the view then useViewDatainstead 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
KeyValuePairis really just a dictionary so if you simply useDictionary<K,V>your code would be easier to work with I believe. -
Anonymous
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.