Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net Mvc - How to have a "controller" in shared view

I have a shared view in my _Layout.cshtml for my header named "_Header.cshtml".

I would like to display text and image from the database, so I need my controller to go in the database and return it to the _Header.cshtml.

How can I do that because the controller called is always different each page the user goes. Is there a way to have controller with Shared View?

Here is the _Layout.cshtml

    <div id="header">         <div id="title">             @Html.Partial("_Header")         </div>          <div id="logindisplay">            @Html.Partial("_CultureChooser")             <br />            @Html.Partial("_LogOnPartial")         </div>          <div id="menucontainer">            @Html.Partial( "_MenuPartial")         </div>     </div>      <div id="main">         @RenderBody()         <div id="footer">         </div>     </div>  </div> 

like image 467
Patrick Desjardins Avatar asked May 09 '11 15:05

Patrick Desjardins


People also ask

How can we call a controller from another view in MVC?

Redirection is very easy, you just call controller and then action in that as above suggested. There is option available to pass parameter too. return RedirectToAction("Tests", new { ID = model.ID, projectName = model. ProjectName });

Can partial view have controller?

It does not require to have a controller action method to call it. Partial view data is dependent of parent model. Caching is not possible as it is tightly bound with parent view (controller action method) and parent's model.

How do you pass data from controller to view and from view to controller?

The other way of passing the data from Controller to View can be by passing an object of the model class to the View. Erase the code of ViewData and pass the object of model class in return view. Import the binding object of model class at the top of Index View and access the properties by @Model.


2 Answers

In your contoller action you could specify the name of the view:

public class MenuController : Controller {     [ChildActionOnly]     public ActionResult Header()     {         var model = ... // go to the database and fetch a model         return View("~/Views/Shared/_Header.cshtml", model);     } } 

Now in your _Layout.cshtml instead of @Html.Partial("_Header") do this:

@Html.Action("Header", "Menu") 
like image 100
Darin Dimitrov Avatar answered Sep 28 '22 21:09

Darin Dimitrov


... 1 year later would just like to add one thing to Dimitrov answer. You can make the controller a little cleaner:

public class MenuController : Controller {     [ChildActionOnly]     public ActionResult Header()     {         var model = ... // go to the database and fetch a model         return Partial("_Header", model);     } } 
like image 33
vidalsasoon Avatar answered Sep 28 '22 20:09

vidalsasoon