.Net Razor-页面之间的共享变量 [英] .Net Razor - sharing variables between pages

查看:75
本文介绍了.Net Razor-页面之间的共享变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于新手问题,我事先表示歉意.我已经习惯了经典ASP,并且正在使用.Net ASP网页(cshtml)进行测试.

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

我创建了一个cshtml页面(Index.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")

在Index.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?

推荐答案

已更新:由于这不是MVC4站点,而是独立的Razor模板,因此MVC的标准答案不适用.此页面显示如何使用PageData对象自定义网站范围的行为

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:

至少可以使用四个对象来完成此任务.也许最简单的是ViewBag.请参见何时使用ViewBag,ViewData ... 了解更多详细信息.

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";
}

您可能会发现这有点问题,因为ViewBag不提供强类型属性.如果ViewBag.topNav不存在,则在访问时它将返回null.

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.

但是,本文中的任何容器都不会提供类型检查.这将我带到可以处理此问题的第四个对象.那就是传递给视图的模型对象.请参见使用ViewModels 了解更多细节.

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
}

在您的控制器中:

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

在索引视图中:

@model IndexViewModel

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

_Header.cshtml:

_Header.cshtml:

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

要注意的最后一项是考虑使用Shared Layout.cshtml,而不是在每个页面中嵌入页眉和页脚.

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

这篇关于.Net Razor-页面之间的共享变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆