Passing Model Data to Layout Page

Kmcnet 686 Reputation points
2024-02-04T00:31:59.2166667+00:00

Hello everyone and thanks for the help in advance. I have a partial view of some header data I want to reuse across several pages and therefore want to place this header within a layout page. This header may be used in other layouts as well. However I cannot figure out how to pass the data into the header through the layout page. The consuming page accepts a view model OrderVM which in turn has HeaderVM and DetailsVM and the header partial view expects HeaderVM. DetailsVM is populated in the page's controller. So how do I get the data into the layout page? Any help would be apprecited.

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,184 questions
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 52,826 Reputation points
    2024-02-04T17:34:50.03+00:00

    There a a couple common ways to pass data to the layout:

    • dedicated viewdata entries (Viewbag.LayoutModel)
    • add layout interface to the view model, so the view model can be cast to the layout model.
    • use a base view model class that defines the layout data.

    as the view model itself is passed via the viewdata, I prefer the first option.


1 additional answer

Sort by: Most helpful
  1. AgaveJoe 25,761 Reputation points
    2024-02-05T20:22:39.64+00:00

    but I am really not understanding how these work. For example, Viewbag.LayoutModel, lets assume I pass OrderVM into ViewBag. Now, the _Header partial view is expecting a type HeaderVM which is included in OrderVM. Do I need to create a reference to OrderVM in the layout page?

    ViewBag is one example of built-in and short lived state management. There are others some longer lived like the database, Session, cookies, cache, URL, etc. I think the problem is you want to persist the data for some period of time.

    Maybe Session is a good choice if you have one web server. Let's assume you use Session["OrderVM"] to store OrderVM. The partial would check if Session["OrderVM"] has data. If Session["OrderVM"] contains data then display the data.