Reputation: 119
I have an MVC 5 site with adminlte template. It's work fine. Now I need pass to some data to _layout page. I need pass to _layout page same info as number of alert, number of email, alert list ecc. I read same document about BaseController where do this operation, i.e. read this data and put in a model, or create an abstract model and put this info into. But is not possibile create this model one time (i.e. on user login controller) and share it in all request without re-create it every controller call? Pratically, as a global singleton variabile. Thanks.
Upvotes: 0
Views: 3916
Reputation: 218722
Looks like a good usecase to use a ChildAction which can be called from the layout view.
So start by creating a view model to represent the data
public class AlertVm
{
public int EmailCount { set; get; }
public int NotificationCount { set; get; }
}
Now create an action method which creates an object of this, set the values and pass to a partial view
[ChildActionOnly]
public ActionResult Alerts()
{
var vm = new AlertVm {EmailCount = 4, NotificationCount = 2};
return PartialView(vm);
}
Now your Alerts.cshtml view, which is strongly typed to our view model, you can render whatever you want.
<div>
<p>@Model.EmailCount emails</p>
<p>@Model.NotificationCount notifications</p>
</div>
And this action method can be invoked from the _Layout.cshtml
view.
<div>@Html.Action("Alerts", "Home")</div>
With this approach, you do not need worry about the creating a view model for every single action. (Ex : Your about page which does not need a view model usually)
Upvotes: 3
Reputation: 1792
Yeah you can create a base view model & make all the model inherit it
public class MyModel
{
public MyBaseClass BaseClass { get; set; }
}
public abstract class MyBaseClass
{
public virtual string MyName
{
get
{
return "MyBaseClass";
}
}
}
public class MyDerievedClass : MyBaseClass
{
public int MyProperty { get; set; }
public override string MyName
{
get
{
return "MyDerievedClass";
}
}
}
only problem is ..the default CreateModel process doesnt register this deafult view model so global.asax is where you tweek it ..
Upvotes: 0