Вопрос

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.

Это было полезно?

Решение 2

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.

Другие советы

Use a partial view.

Partial view is like a regular view with a file extension .cshtml. You can use partial views in a situation where we need a header, footer reused for an MVC web application. You can say that it’s like a user control concept in ASP.NET.

You can use:

  • @Html.Action()- which will call an action of a certain controller and return a view result.
  • @Html.Partial() - which will generate a partial view
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top