我想将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>
主页 - &gt; Index.cshtml
@{
Layout = "~/Views/Shared/SiteMaster.cshtml";
}
<div>Test</div>
App_Start - &gt; 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 }
);
}
答案 0 :(得分:1)
您可以使用全局ActionFilter:
来完成public class MasterPageTitleFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
filterContext.Controller.ViewBag.PageTitle = "Show this text into my MasterPage";
base.OnActionExecuted(filterContext);
}
}
如果您将此过滤器设置为某个操作,则会在生成视图之前触发该过滤器,以便在ViewBag
中添加您的标题。
要将其用于每个操作/控制器而不标记所有操作/控制器,请将其添加到全局过滤器注册中:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
// other filters to add
filters.Add(new MasterPageTitleFilterAttribute());
}
答案 1 :(得分:0)
我相信你只需要将你的viewbag分配到你的homecontroller的索引动作中。您的站点管理员操作未被调用。
答案 2 :(得分:0)
您可以创建一个包含覆盖方法
的基本控制器public class BaseController: Controller
{
public override void OnActionExecuting(ActionExecutedContext filterContext)
{
filterContext.Controller.ViewBag.PageTitle = "Show this text into my MasterPage";
//base.OnActionExecuted(filterContext);
}
}
然后你将从BaseController继承你的其他控制器。因此,您每次都会在masterPage ..
中访问ViewBag.PageTitlepublic class HomeController : BaseController
{
...
}
答案 3 :(得分:-1)
您需要在操作中指定Viewbag。
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.PageTitle = "Show this text into my MasterPage";
return View();
}
}