How do I access a ViewBag.Title after it has been set by the underlying View?

谁说胖子不能爱 提交于 2020-01-14 12:37:20

问题


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


回答1:


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

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

@{
   SetTitle("Home Page");
}


and

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

}



来源:https://stackoverflow.com/questions/6216600/how-do-i-access-a-viewbag-title-after-it-has-been-set-by-the-underlying-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!