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>
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 });
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.
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.
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")
... 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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With