Home > Software design >  Differences and benefits of PageModel vs ViewData in Razor Pages
Differences and benefits of PageModel vs ViewData in Razor Pages

Time:05-31

I cannot find any clear explanation on this.

I am trying to understand the differences and benefits of PageModel vs ViewData as a tool to pass data from C# code to cshtml for rendering in Razor Pages. What would be an impact on performance, reliability, testability?

Using ASP.NET 6.

CodePudding user response:

PageModel is strong typing: IntelliSense and compile-time checking when accessing properties of the Model in a content page.

ViewData can be used as the ViewData attribute on model properties. ViewData is shared with the layout page (and any partial pages called by the content page or the layout), so the attribute makes it easy to pass typed data from the PageModel to the layout page or partials without having to explicitly assign it to the ViewData dictionary.

Example:

public class IndexModel : PageModel
{
    [ViewData]
    public string Message { get; set; }
    public void OnGet()
    {
        Message = "Hello World";
    }
}

Add <h2>@ViewData["Message"]</h2> into layout page.

enter image description here

  • Related