.Net Razor - sharing variables between pages

2019-02-26 08:22发布

问题:

I apologize in advance for the noob question. I am used to Classic ASP and am testing the water with .Net ASP Web Pages (cshtml).

I created a cshtml page (Index.cshtml) that will be including a header and a footer. I am including them using

@RenderPage("~/Shared/_Header.cshtml")
@RenderPage("~/Shared/_Footer.cshtml")

At the top of the Index.cshtml, I want to set a variable:

var topNav = "services";

I would like to access this variable from the header and/or footer. How can I accomplish this?

回答1:

Updated: Since this is not a MVC4 site, but standalone Razor templates, the standard answers for MVC don't apply. This page shows how to pass data between pages using the PageData object Customizing Site-Wide Behavior

My original answer doesn't really apply, but the concepts are still valid:

There are at least four objects that can be used to accomplish this. Perhaps the easiest would be ViewBag. See When to use ViewBag, ViewData... for more specifics.

@{
    ViewBag.topNav = "services";
}

You may find that a bit problematic, since ViewBag does not provide strongly typed properties. if ViewBag.topNav does not exist, it will return null when accessed.

However, none of the containers in the article will provide type checking. This brings me to the fourth object which can handle this. That is the model object which is passed to the view. See Using ViewModels for more specifics.

public class IndexViewModel {
   public string TopNav { get; set; }
   // other view properties here
}

In your controller:

public ActionResult Index() {
   var model = new IndexViewModel {
      TopNav = "services",
      // set other properties here
   }
   return View(model);
}

And in the index view:

@model IndexViewModel

@RenderPage("~/Shared/_Header.cshtml",Model)

_Header.cshtml:

@model IndexViewModel
<h2>@Model.topNav</h2>

One last item to note is to consider using a Shared Layout.cshtml instead of embedding the header and footer in each page.



回答2:

One of the options is to use ViewBag:

http://weblogs.asp.net/hajan/viewbag-dynamic-in-asp-net-mvc-3-rc-2