Search code examples
c#asp.net-mvcrazorengine

How to create "header with load" in MVC Razor layout page?


I am trying to create something like a user control in traditional webforms which is to be used in the master page. When it rendered an event is fired to load the data.

How to implement the similar functionality in MVC Razor layout? With my header having its own controller view and model.


Solution

  • You can use @Html.Action which will let you invoke a controller action and render its respective view.

    <body>
        @Html.Action("MyAction", "MyController")
    </body>
    

    where MyAction is an action within MyController which returns a view.

    You can also apply the ChildActionOnly attribute to that action to ensure that the only way it can be invoked is through the Action method.