What's the best method to be overloaded in ViewPage for inserting some script to all ViewPage?
I want to insert some script that is required for my JavaScript library in all view pages. I know that Asp.net MVC is built on Asp.net Framework. Therefore, I can override many methods in “System.Web.UI.Page” class that is a parent of “System.开发者_如何学JAVAWeb.Mvc.ViewPage” class.
Nevertheless, I can do it by override Render method but it makes all view pages be invalid for XHTML 1.0 strict. Correct JavaScript must be placed in header tag of HTML document.
public class ViewPage<TModel> : ViewPage where TModel : class
{
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
base.Render(writer);
writer.Write("<script type='text/javascript>applicationPath = window.applicationPath = 'somePath';</script>");
}
}
Thanks,
PS. I know I can create some code in each master page for doing that. However, it is a quite complicate for other developers to start using my JavaScript source code.
Don't do it in code; do it in markup. Add the script tag to your Site.Master, in the correct, valid place.
I just see head of both View Page & View Master Page always run at server. Please look at the following templates.
Default Template of ViewPage
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<div>
</div>
</body>
</html>
Default Template of ViewMasterPage
<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
</head>
<body>
<div>
<asp:ContentPlaceHolder ID="MainContent" runat="server">
</asp:ContentPlaceHolder>
</div>
</body>
</html>
Therefore, it is very easy to solve this question by adding some control to header control.
public class ViewPage : mvc.ViewPage
{
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
if (Header == null)
throw new Exception("Header object is null. Please set header runat=\"server\".");
Header.Controls.Add(new LiteralControl(CommonHelper.JavaScript(MvcUtils.GetApplicationUrl(Request) ,string.Empty)));
base.Render(writer);
}
}
精彩评论