1

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?

Ashley
  • 123
  • 2
  • 7

2 Answers2

0

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.

Community
  • 1
  • 1
Georg Patscheider
  • 8,808
  • 1
  • 21
  • 34
  • 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
0

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 :)

Ashley
  • 123
  • 2
  • 7