I have a website which allows users to send messages to eachother. My layout on the top has a notification bar, which shows the number of unread messages. My table with messages has a property of Unread (true, false). I can easily search for unread messages for the current user, I just don't know how to send it to layout. Is there a controller I can use to send to a layout?
-
https://gyazo.com/679499bcb8bef59b9d5843f068c253d2 That's the picture of the top bar, it's in shared layout. – Ashley Feb 13 '17 at 12:48
-
You can Render Partial View In your layout page – Ghanshyam Singh Feb 13 '17 at 12:50
-
But where do I call this controller that renders partial, so it updates everytime the user does anything on the website? – Ashley Feb 13 '17 at 12:53
-
Will that partial view be rendered and called again each time the user refreshes or clicks any link on the website? – Ashley Feb 13 '17 at 12:57
-
If this is something that you want refreshed everytime the user does something.. then put this in your `_Layout` page. – Grizzly Feb 13 '17 at 13:00
-
Yes Partial View will be rendered each time user refreshes – Ghanshyam Singh Feb 13 '17 at 13:10
2 Answers
You can define that your layout pages use a model. I would recommend using an interface as model.
public interface IMessageNotification {
public int UnreadMessagesCount {get; set;}
}
All ViewModels that use the layout page have to implement this interface. You can access it in the Layout.cshtml like this:
@model IMessageNotification
<div class="myNotification">@Model.UnreadMessagesCount</div>
See ASP.NET MVC Razor pass model to layout
Another way would be to define a section in the layout that acts as placeholder for the notification, and every view can render the notification how it wants.
Layout:
@* No model directive required *@
@if (IsSectionDefined("Notification")) {
@RenderSection("Notification")
}
Concrete View (SomeConcreteViewModel has property UnreadMessagesCount):
@model SomeConcreteViewModel
@section Notification {
<div class="myNotification">@Model.UnreadMessagesCount</div>
}
As for the controller: you can use a helper class that fills the required data into the IMessageNotification interface implemented by the viewmodels. Call this in every action that renders a view using this layout.

- 1
- 1

- 9,357
- 1
- 26
- 36
-
Thank you for the answer. I never knew that you could use a viewmodel for the layout. I used different approach. I created a partial view, and used a controller to call it. I queried the DB for unread messages, and sent the count via ViewBag. I call it with @Html.Action. Thanks for your effort, Georg :) – Ashley Feb 13 '17 at 13:19
I created a partial view, and used a controller to call it. I queried the DB for unread messages, and sent the count via ViewBag. I call it with @Html.Action. Didn't know this gets rendered each time user refreshes a web page. Thank you all :)

- 133
- 2
- 7