Global variable in asp-net mvc views

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

Now imagine a gmail-like scenario in which you will have an Inbox (n) element in your menu, where n is the number of unread messages. Is there a clean way to pass the variable n to all views using the Site.Master main page?

Sort of:

<%: Html.ActionLink("Inbox - " + ViewData["n"], "Index", "Home") %>
+3
source share
4 answers

You can use child actions together with the Html.Action and Html.RenderAction helpers . So let's take a closer look at an example.

, , ( ):

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

:

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

(~/Views/Inbox/Index.ascx):

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

, , , :

<div class="leftMenu">
    <% Html.RenderAction("Index", "Inbox"); %>
</div>
+4

_ViewStart.cshtml( ) ;)

+1

ViewData[]. () .

:

ViewData["UnreadMessages"] = "5";

.

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 the view data returns objects, just delete the number as a string, and then you can use it in exactly the same way

<%: Html.ActionLink("Inbox - " +ViewData["n"].ToString(), "Index", "Home") %>
0
source

Source: https://habr.com/ru/post/1793940/


All Articles