Reputation: 1227
I have "LoginBox" section defined in _Layout.cshtml, and its model is AccountModel. So it'll always display in every page, but i want to know that, do i really have to pass that model in every ViewModel? My example IndexViewModel is like this:
public class IndexViewModel
{
public BulletinModel Bulletin { get; set; }
public CategoryModel Category { get; set; }
}
I can add this model to this viewmodel but do i really have to do that in every viewmodel? Can i define it like a global model, i don't know if it makes any performance problem.
Thanks.
Upvotes: 1
Views: 692
Reputation: 6218
If you don't want to pass your additional Model to each of your main ViewModel, you may also want to try with @Html.RenderAction(ActionName, ControllerName)
@{ Html.RenderAction("ActionName", "ControllerName"); }
Upvotes: 1
Reputation:
No, you absolutely don't have to define it in every ViewModel. Typically, in the _Layout View you will have persisting elements of the layout defined as such:
@using YourModelsNS
@* layout markup omitted for brevity *@
<div id="header">
<div id="title">
<h1>My MVC Application</h1>
</div>
<div id="logindisplay">
@Html.Partial("_LogOnPartial", new YourMode() { SomeString = "Test" })
</div>
<div id="menucontainer">
<ul id="menu">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Test", "Test", "Test")</li>
</ul>
</div>
</div>
<div id="main">
@RenderBody()
</div>
<div id="footer">
</div>
</div>
Notice here that in the View you see @Html.Partial("_LogOnPartial")
. This is what then renders the particular View, _LogOnPartial.cshtml. Which contains this markup:
@model YourModelNS.YourModel
@if(Request.IsAuthenticated) {
<text>Welcome <strong>@User.Identity.Name</strong>!
[ @Html.ActionLink("Log Off", "LogOff", "Account") ]</text>
}
else {
@:[ @Html.ActionLink("Log On", "LogOn", "Account") ]
}
@Model.SomeString
This is separate from the content pages that are rendered through @RenderBody(), therefore you won't be needing to include separate concerns within all ViewModels or Views themselves.
EDIT: Code has been edited to pass a model object to the Partial View. Now every content page (by RenderBody()
is ignorant to the YourModel
Model, and their corresponding ViewModels don't have to know anything about it.
Disclaimer: I do not recommend the above code practice, the omission of Controller logic is simply to focus on the question at hand.
Upvotes: 1