ViewBag in asp.net core

S A 81 Reputation points
2022-04-01T12:06:37.027+00:00

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

ASP.NET Core
ASP.NET Core
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
    2022-04-01T14:32:09.237+00:00

    Razor Pages use TempData.


  2. Michael Taylor 49,701 Reputation points
    2022-04-01T15:29:49.287+00:00

    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
       [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 use Dictionary<K,V> your code would be easier to work with I believe.


  3. Zhi Lv - MSFT 32,051 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:

    189631-image.png


    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


  4. S A 81 Reputation points
    2022-04-07T14:34:10.677+00:00

    Thank you very much for everyone.

    0 comments No comments