Asp.net mvc 3 如何让我的ViewContext.ViewBag使用我的代码?
我正在尝试创建一个HtmlHelper,它允许我在父视图和子视图之间进行通信。我从这里得到了教程: 首先,我创建了如下的类和方法:Asp.net mvc 3 如何让我的ViewContext.ViewBag使用我的代码?,asp.net-mvc-3,Asp.net Mvc 3,我正在尝试创建一个HtmlHelper,它允许我在父视图和子视图之间进行通信。我从这里得到了教程: 首先,我创建了如下的类和方法: namespace SchoolIn.Helpers { public static class ViewBagHelpers { public static dynamic GetPageViewBag(this HtmlHelper html) { if (html == null || html.
namespace SchoolIn.Helpers
{
public static class ViewBagHelpers
{
public static dynamic GetPageViewBag(this HtmlHelper html)
{
if (html == null || html.ViewContext == null) //this means that the page is root or parial view
{
return html.ViewData;
}
ControllerBase controller = html.ViewContext.Controller;
while (controller.ControllerContext.IsChildAction) //traverse hierachy to get root controller
{
controller = controller.ControllerContext.ParentActionViewContext.Controller;
}
return controller.ViewBag;
}
}
}
在子视图中,我添加了一个using语句:
@using SchoolIn.Helpers
及
在父视图中,我尝试执行以下操作:
@{ ViewBag.Title = ViewContext.ViewBag.PageTitle }
所以我想我有两个问题。第一个是我没有像教程一样访问html.ViewBag的权限,在父视图中我无法
ViewContex.ViewBag.
你知道我该怎么做吗?谢谢你的帮助。经过几次调整后,我终于让它工作了。请确保语法正确,并且在呈现部分内容后设置了标题 版面页面(\u Layout.cshtml):
@using SchoolIn.Helpers
@* Nb. The example did not include the call to partial. *@
@Html.Partial("_Child")
@* The following line must appear after the partial is rendered for the ViewBag to have been set. *@
@* Nb. The example was missing the semicolon. *@
@{ ViewBag.Title = ViewContext.ViewBag.PageTitle; }
@using SchoolIn.Helpers
@{Html.GetPageViewBag().PageTitle = "My Custom Property Readable By Parent View"; }
部分视图(\u Child.cshtml):
@using SchoolIn.Helpers
@* Nb. The example did not include the call to partial. *@
@Html.Partial("_Child")
@* The following line must appear after the partial is rendered for the ViewBag to have been set. *@
@* Nb. The example was missing the semicolon. *@
@{ ViewBag.Title = ViewContext.ViewBag.PageTitle; }
@using SchoolIn.Helpers
@{Html.GetPageViewBag().PageTitle = "My Custom Property Readable By Parent View"; }
是什么让你试图从偏执的观点回到观点?是否确实需要这样做,或者是否有更好的方法来设计布局/视图/分区/模型?没有错误消息,但标题也不显示。我发现需要执行此操作才能访问帮助文件和视图中的ViewBag属性:.ViewContext.Controller.ViewBag。我的部分视图也是使用@Ajax.ActionLink()调用的。我想知道这是否与任何事情有关。您在问题中从未提到您使用的是Ajax,但是是的,如果您使用的是Ajax,那么设置标题的方法将不起作用。您正在使用的方法设置ViewBag中的标题,该标题仅在服务器端可用。一旦该视图被发送到浏览器,它就不再具有对ViewBag的访问权限,因此无法使用您的方法设置标题。如果您使用Ajax检索部分内容,则可以在检索页面时使用,尽管不建议用于SEO目的。