asp.net-mvc-3 – 为什么_ViewStart.cshtml访问ViewBag对象?

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-3 – 为什么_ViewStart.cshtml访问ViewBag对象?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有我的/ Views文件夹中的默认_ViewStart.cshtml。我想能够访问我的ViewBag对象,所以我可以设置所有我的视图的默认标题

但是,用:

@{
    Layout = "~/Views/Shared/SiteLayout.cshtml";
    ViewBag.Title = "bytecourse - Online Courses in Technology";
}

我得到“名称’ViewBag’在当前上下文中不存在”作为运行时错误

我需要做什么?

解决方法

简而言之…使用控制器的查看包。
ViewContext.Controller.ViewBag.MyVar = "myVal";

@ViewContext.Controller.ViewBag.MyVar

================================================== =============

这里有很好的信息:http://forums.asp.net/post/4254825.aspx

================================================== =============

Generally,ViewData[“StoreName”] is same as ViewBag.StoreName

Also,Controller.ViewData[“StoreName”] = Controller.StoreName =
ViewContext.Controller.ViewBag.StoreName
=ViewContext.Controller.ViewData[“StoreName”]

But every view and partial view gets its own instance of viewdata.

07001

================================================== =============

这里有另一个解决方案:http://stackoverflow.com/a/4834382/291753

================================================== =============

原文链接:https://www.f2er.com/aspnet/254239.html

猜你在找的asp.Net相关文章