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>
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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")
Method 2
… 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);
}
}
Method 3
Create an action in one of your controllers to render the header view, then simply call @Html.RenderAction(“Header”) within the _Layout.cshtml.
You can also pass a model into the RenderAction method if required.
Method 4
While the RenderAction approach that WDuffy provided works well, I recently blogged about this very topic using another approach using IoC:
http://crazorsharp.blogspot.com/2011/03/master-page-model-in-aspnet-mvc-3-using.html
Method 5
I hope the question you have asked is Like….
Can we have a controller for a Shared Layout View.
Simple answer is No.
To achieve this goal you have to create a partial view for the Same purpose and put it into you shared Layout. By that means you can achieve you Goal
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0