【发布时间】:2013-11-15 22:48:06
【问题描述】:
我想将ViewBag 返回到我的母版页,但我对 MVC Razor 没有太多经验,所以我不知道如何解决我的问题,这是我的代码:
控制器:
MasterController.cs
public class SharedController : Controller
{
public ActionResult SiteMaster()
{
ViewBag.PageTitle = "Show this text into my MasterPage";
return View();
}
}
和
HomeController.cs
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
观看次数:
共享 -> SiteMaster.cshtml
<html>
<head></head>
<body>
<div>@ViewBag.PageTitle</div> //Doesn't work
<div>@RenderBody()</div>
</body>
</html>
首页 -> Index.cshtml
@{
Layout = "~/Views/Shared/SiteMaster.cshtml";
}
<div>Test</div>
App_Start -> RouteConfig.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
【问题讨论】:
-
您希望每次显示视图时都显示
ViewBag.PageTitle吗? -
是的,因为我有母版页,所以我需要在包含
Master Page的每个页面上显示View Bag。
标签: c# asp.net-mvc-4 razor controller master-pages