在底层视图设置 ViewBag.Title 后,如何访问它?
事情是这样的。我有一个 MVC 操作,在该操作上,我应用了自定义 ActionFilterAttribute 来使反序列化工作。现在,我想做的是根据此视图内设置的 ViewBag.Title 设置一些标头。
我尝试将 ViewResult 包装在自己的 ViewResult 中,并覆盖 ExecuteResult,但 ViewBag 始终为空:-(。
这是否可能,或者 MVC 引擎在执行 _layout 后是否会重置 ViewBag?
更新: 让我发布一些代码示例,以更清楚地说明我想要做什么。我有一个电子邮件服务,我可以在其中从 MVC 视图呈现正文。所以我的视图如下所示:
@{ViewBag.Title = "EventCreated";}
Something that ressembles an email message here.
现在我有一个控制器,其操作如下所示:
public ActionResult HelloWorld(MailView<HelloWorldMessage> msg)
{
Response.Headers["subject"] = "Test subject";
return View(msg);
}
我想让 Headers["subject"] 语句看起来像 Response.Headers["subject"] = ViewBag.Title;我希望能够让视图认为它正在处理正常的网页。
我尝试使用 ActionFilterAttribute 并覆盖 OnResultExecuted 但无法使其工作。
一种可能的选择是将其设置在布局页面上,并根据某些标准实际决定使用哪种布局。这样我仍然可以让 Reponse 的东西远离我的视图,但让它变得相当干净。你怎么认为?
谢谢, 安泽
Here's the thing. I have a MVC Action, and on that action, I have applied a custom ActionFilterAttribute to get the deserialization working. Now, what I want to do, is set some header based on the ViewBag.Title that is set inside this view.
I've tried wrapping the ViewResult in my own, and overriding the ExecuteResult but the ViewBag is always empty :-(.
Is this even possible or does the MVC engine reset the ViewBag once the _layout is executed?
Update:
Let me post some code samples, to make clearer what I want to do. I have an email service, where I render the body from a MVC view. So my view looks like this:
@{ViewBag.Title = "EventCreated";}
Something that ressembles an email message here.
Now I have a Controller, with an action that looks something like this:
public ActionResult HelloWorld(MailView<HelloWorldMessage> msg)
{
Response.Headers["subject"] = "Test subject";
return View(msg);
}
I want to make that Headers["subject"] statement to look like Response.Headers["subject"] = ViewBag.Title; and I want to do be able to let the View think it's handling a normal web page.
I've tried using an ActionFilterAttribute and overriding OnResultExecuted but couldn't get it to work.
One possible option is to set it on the layout page and actually decide based on certain criteria which layout to use. That way I can still keep the Reponse thing away from my views but make it rather clean. What do you think?
Thanks,
Anže
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个 - 分配视图结果的输出
为什么这一切 - 当你说“我希望能够让视图认为它正在处理正常的网页”时,我没有遵循。
编辑:
那么为什么不通过视图中的辅助方法来设置它呢?
丙氨酸
和
Try this - assign the output of the view result
Why all of this though - I didn't follow when you said "and I want to do be able to let the View think it's handling a normal web page."
Edit:
Why don't you then just set this via a helper method in your View?
ala
and