如何访问一个ViewBag.Title后,它已被由基础视图中设置? [英] How do I access a ViewBag.Title after it has been set by the underlying View?

查看:2175
本文介绍了如何访问一个ViewBag.Title后,它已被由基础视图中设置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里的事情。我有一个MVC的行动,并采取行动,我已经申请自定义ActionFilterAttribute得到反序列化工作。现在,我想要做的,是集基础上,ViewBag.Title一些头被设置该视图中。

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.

我试过包裹的ViewResult在我自己的,并重写的ExecuteReuslt但ViewBag总是空: - (

I've tried wrapping the ViewResult in my own, and overriding the ExecuteResult but the ViewBag is always empty :-(.

这甚至可能还是一次执行_layout的MVC引擎重置ViewBag?

Is this even possible or does the MVC engine reset the ViewBag once the _layout is executed?

更新:
让我张贴一些code样本,以更清楚我想做的事情。我有一个电子邮件服务,在那里我使身体从MVC视图。所以我的看法是这样的:

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);
        }

我要作出这样的标题[主题]声明看起来像Response.Headers [主题] = ViewBag.Title;我想这样做能够让观认为它处理正常的网页。

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.

我使用的是ActionFilterAttribute尝试和压倒一切的OnResultExecuted,但不能得到它的工作。

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

推荐答案

试试这个 - 分配视图结果输出

Try this - assign the output of the view result


var output = View(msg);
//do your other viewbag stuff here
return output;

为什么这一切,虽然 - 我没有你说遵循我想要做能够让观认为它处理正常网页

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."

修改
你为什么不那么就通过在你查看一个辅助方法设置这个?
ALA

Edit: Why don't you then just set this via a helper method in your View? ala


@{
   SetTitle("Home Page");
}



@functions {
    public void SetTitle(string title)
    {
        ViewBag.Title = title;
        Response.Headers.Add("title", title);
    }

}

这篇关于如何访问一个ViewBag.Title后,它已被由基础视图中设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆