6

In my web application I placed the menu on a partial view and load it from the Site.Master.

Now imagine a gmail like scenario where on your menu you'll have an Inbox(n) item where n is the number of unreaded mails. Is there a clean way to pass the n variable to all of the views that use the Site.Master masterpage?

Something like:

<%: Html.ActionLink("Inbox - " + ViewData["n"], "Index", "Home") %>
dcarneiro
  • 7,060
  • 11
  • 51
  • 74
  • Possible duplicate of [Access Viewbag property on all views](https://stackoverflow.com/questions/27308524/access-viewbag-property-on-all-views) – tecla Jun 16 '17 at 23:56

4 Answers4

4

You could use child actions along with the Html.Action and Html.RenderAction helpers. So let's elaborate with an example.

As always you start with a view model that will represent the information you want to show on this particular view (or in this case partial view):

public class InboxViewModel
{
    public int NumberOfUnreadMails { get; set; }
}

then a controller:

public class InboxController : Controller
{
    public ActionResult Index()
    {
        InboxViewModel model = ... // Repository, DI into the controller, ...
        return View(model);
    }
}

then a corresponding view (~/Views/Inbox/Index.ascx):

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%: Html.ActionLink("Inbox - " + Model.NumberOfUnreadMails, "Index", "Home") %>

and finally embed this in your master page so that it is available on all views:

<div class="leftMenu">
    <% Html.RenderAction("Index", "Inbox"); %>
</div>
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • This works just great. Didn't knew about the RenderAction, only the RenderPartial. Thanks for the help. – dcarneiro Feb 23 '11 at 09:56
1

just define Global objects in _ViewStart.cshtml (views root folder), and use them all around views in project ;)

Søren
  • 6,517
  • 6
  • 43
  • 47
0

Consider keeping this in ViewData[]. This is how you can easily share data between different (partial) views.

Controller:

ViewData["UnreadMessages"] = "5";

All views can simply access this property.

p.campbell
  • 98,673
  • 67
  • 256
  • 322
  • The problem with this is that I have to set ViewData["UnreadMessages"] on all my actions. I was looking for a cleaner method. – dcarneiro Feb 23 '11 at 09:45
0

You should be able to do it the way you did in the example, just tell it to make the value a string, since view data returns objects, just unbox the number as a string and then you could use it just like that

<%: Html.ActionLink("Inbox - " +ViewData["n"].ToString(), "Index", "Home") %>
Francisco Noriega
  • 13,725
  • 11
  • 47
  • 72
  • The problem with this is that I have to set ViewData["UnreadMessages"] on all my actions. I was looking for a cleaner method – dcarneiro Feb 23 '11 at 10:30