Reputation: 3735
I am going to inject some elements in every view of our Asp.Net MVC application. so to do that (I found this: Custom WebViewPage inject code when razor template is rendering answer) I have subclassed the WebViewPage
and I have overridden the ExecutePageHierarchy
like below:
public override void ExecutePageHierarchy()
{
base.ExecutePageHierarchy();
string output = Output.ToString();
if (MyHelper.InitializationRequired)
output = MyHelper.GetPageHeader() + output + MyHelper.GetPageFooter();
//--------------
Response.Clear();
Response.Write(output);
Response.End();
}
by this code we can wrap all of the output markup with some header and some footer elements such as scripts or additional tags which i want to do that.
BUT in this way we lost the Layout
completely! because of clearing the response.
my main question is that, how to inject some HTML markups exactly before or exactly after WebViewPage
's output by preserving the content of response which maybe there are some other views or the layout?
Upvotes: 0
Views: 496
Reputation: 3735
Finally i found a trick to do it by this way:
public override void ExecutePageHierarchy()
{
var tmp = OutputStack.Pop();
var myWriter = new StringWriter();
OutputStack.Push(myWriter);
base.ExecutePageHierarchy();
tmp.Write(
string.Format("<div> Header of [{0}]</div> {1} <div> Footer of [{0}]</div>",
VirtualPath,
myWriter.ToString()));
}
it works well generally and it wraps the output of view by header and footer. but in my scenario i should able to access to some flags which will assigned on executing view. so i must check them after view execution:
public override void ExecutePageHierarchy()
{
var tmp = OutputStack.Pop();
var myWriter = new StringWriter();
OutputStack.Push(myWriter);
base.ExecutePageHierarchy();
if (MyHelper.InitializationRequired)
tmp.Write(
string.Format("<div> Header of [{0}]</div> {1} <div> Footer of [{0}]</div>",
VirtualPath,
myWriter.ToString()));
else
tmp.Write(myWriter.ToString());
}
this approach works well for me. so i posted it, maybe help some one;)
Upvotes: 2
Reputation: 902
You should use the layout system of MVC ... It's full featured to have a master layout schema :=)
Upvotes: 1