Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC: How to get controller to render partial view initiated from the view

In my MVC5 project I want to create a menu in a partial view. This menu is dynamic in the sense that it is built from content in my database. Thus I have a controller taking care of creating my menu and returning the menu model to my partial view:

public PartialViewResult GetMenu() {    MenuStructuredModel menuStructuredModel = menuBusiness.GetStructuredMenu();     return PartialView("~/Views/Shared/MenuPartial", menuStructuredModel); } 

In my partial view called MenuPartial I want to use razor to iterate over my menu items, like:

@model MyApp.Models.Menu.MenuStructuredModel  <div class="list-group panel">     @foreach (var category in Model.ViewTypes[0].Categories)     {         <a href="#" class="list-group-item lg-green" data-parent="#MainMenu">@category.ShownName</a>     } </div> 

Now the problem is the view in which I insert the partial view. If in the view I simply do:

@Html.Partial("MenuPartial") 

It won't call the controller to populate the model with data first. What I want is to let the controller return the partial. But I don't know how to do this from the view. In pseudo code I would like to do something like:

@Html.RenderPartialFromController("/MyController/GetMenu") 
like image 402
brinch Avatar asked Mar 31 '15 22:03

brinch


People also ask

How do you render a partial view inside a view in MVC?

Partial function which renders the Partial View. The name of the View and the object of the CustomerModel class are passed to the @Html. Partial function. In order to add Partial View, you will need to Right Click inside the Controller class and click on the Add View option in order to create a View for the Controller.

How do you return a partial view from controller?

In ASP.NET Core MVC, a controller's ViewResult is capable of returning either a view or a partial view. In Razor Pages, a PageModel can return a partial view represented as a PartialViewResult object. Referencing and rendering partial views is described in the Reference a partial view section.


2 Answers

Thanks to Stephen Muecke and Erick Cortorreal I got it to work.

This is what the controller should look like:

[ChildActionOnly] public PartialViewResult GetMenu() {    MenuStructuredModel menuStructuredModel = menuBusiness.GetStructuredMenu();     return PartialView("~/Views/Shared/MenuPartial", menuStructuredModel); } 

And it may called like:

@Html.Action("GetMenu", "Home")

(Hence GetMenu() is declared in the HomeController in my example).

The controller is now called (and the model is populated) prior to the partial view is rendered.

like image 156
brinch Avatar answered Sep 20 '22 22:09

brinch


You should use: @Html.RenderAction or @Html.Action.

like image 24
Erick Cortorreal Avatar answered Sep 21 '22 22:09

Erick Cortorreal