ViewBag in core

S A 81 Reputation points

Do you know how to activate ViewBag in PageModel (x.cshtml.cs files) of core 3.1? Thanks

A set of technologies in the .NET Framework for building web applications and XML web services.
4,280 questions
0 comments No comments
{count} votes

4 answers

Sort by: Most helpful
  1. AgaveJoe 26,671 Reputation points

    Razor Pages use TempData.

  2. Michael Taylor 49,701 Reputation points

    You do not have access to ViewBag inside PageModel. There are hacks to get it to work but there is no reason to do so.

    To store data temporarily you must use TempData or ViewData. If you need access to the data in the view then use ViewData instead of ViewBag.

    public class Index: PageModel
       //Preferred approach
       public KeyValuPair<string, string>[] Values { get; set; }
       public void OnGet ()
          //Only if really, really needed
          ViewData["Values"] = kvpArray;
       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 use Dictionary<K,V> your code would be easier to work with I believe.

  3. Zhi Lv - MSFT 32,051 Reputation points Microsoft Vendor

    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,

  4. S A 81 Reputation points

    Thank you very much for everyone.

    0 comments No comments