海洋工作室——网站建设专家:Calling JavaScript from ASP.NET Master Page and Content Pages - Part I
2009-09-09 23:10
696 查看
[align=justify]Calling JavaScript from Master and Content Pages confuses a lot of developers. In this article, we will see some common problems and their solutions of calling JavaScript from a Master/Content page. This article is Part I of the two part series and will cover JavaScript in Master Pages. The next article will cover JavaScript in Content pages.[/align]
[align=justify]Update: Part II of this article can be read over here Calling JavaScript from ASP.NET Master Page and Content Pages - Part II[/align]
[align=justify]Call JavaScript From Master Page[/align]
[align=justify]You can call an existing JavaScript function from a Master Page or can create one on the fly. Here are some common scenarios: [/align]
[align=justify]1. Create a JavaScript function on the fly and call the JavaScript function in the MasterPage Page_Load() event[/align]
[align=justify]C#[/align]
protected void Page_Load(object sender, EventArgs e)
{
string someScript = "";
someScript = "<script language='javascript'>alert('Called from CodeBehind');</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "onload", someScript);
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim someScript As String = ""
someScript = "<script language='javascript'>alert('Called from CodeBehind');</script>"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "onload", someScript)
End Sub
[align=justify][/align]
[align=justify]The Page.ClientScript.RegisterStartupScript() allows you to emit client-side script blocks from code behind. More info can be found over here http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerstartupscript.aspx[/align] [align=justify]2. Call an existing JavaScript function on MasterPage Page_Load() event[/align]
[align=justify]Let us assume you have an existing JavaScript function declared in between the <head> tags, then here’s how to call that function from Page_Load()[/align]
<head runat="server">
<title></title>
<script type="text/javascript">
function invokeMeMaster() {
alert('I was invoked from Master');
}
</script>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.ClientScript.IsStartupScriptRegistered("alert"))
{
Page.ClientScript.RegisterStartupScript
(this.GetType(), "alert", "invokeMeMaster();", true);
}
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (Not Page.ClientScript.IsStartupScriptRegistered("alert")) Then
Page.ClientScript.RegisterStartupScript(Me.GetType(), "alert", "invokeMeMaster();", True)
End If
End Sub
3. Call JavaScript function from MasterPage on Button click
If you want to call a JavaScript function on a Button click, then here’s how to do so:
<head runat="server">
<title></title>
<script type="text/javascript">
function invokeMeMaster() {
alert('I was invoked from Masterdotnetcurry');
}
</script>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
In the <body> tag, add a Button and use the OnClientClick to call this function
<asp:Button ID="btnMaster" runat="server" Text="Button" OnClientClick="return invokeMeMaster();"/>
[align=justify]The OnClientClick() is called before the postback occurs. This gives us a place to check for some condition and cancel the submit if the condition is not satisfied. We will see an example in Tip 6.[/align]
[align=justify]4. Access a control on the MasterPage using JavaScript[/align]
[align=justify]If you have a control on the MasterPage and need to access it using JavaScript, then here’s how to do so. In this sample, we will test the length of the TextBox to see if there are 5 or more letters. If the number of letters is less than 5, the form submit will be cancelled.[/align]
[align=justify]Add a TextBox and a Button control in the MasterPage (outside the ContentPlaceHolder) as shown below[/align]
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="panelMaster" GroupingText="MasterPage controls" runat="server">
<asp:TextBox ID="txtMaster" runat="server"></asp:TextBox>
<asp:Button ID="btnMaster" runat="server" Text="Button" OnClientClick="return accessMasterControl();" />
<br />
</asp:Panel>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
In the <head> element of the MasterPage, add the following code:
<head runat="server">
<title></title>
<script type="text/javascript">
function accessMasterControl() {
if (document.getElementById('<%=txtMaster.ClientID%>').value.length <= 5) {
alert('Minimum 5 characters required')
return false;
}
else { return true;}
}
</script>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
5. Access a control on the Content Page from a MasterPage using JavaScript
If you have a control on the Content Page which has to be accessed in the MasterPage using JavaScript, then here’s how to do so:
On the Content Page, create a TextBox as shown below :
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:Panel ID="panelContent" GroupingText="ContentPage Controls" runat="server">
<asp:TextBox ID="txtContent" runat="server"></asp:TextBox>
</asp:Panel>
</asp:Content>
Now access and populate the TextBox ‘txtContent’ from the MasterPage
<head runat="server">
<title></title>
<script type="text/javascript">
function accessControlContentPage() {
var txtCont = document.getElementById('<%= Page.Master.FindControl("ContentPlaceHolder1").FindControl("txtContent").ClientID %>');
txtCont.value = "I got populated using Master Page";
}
</script>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
[align=justify]6. Ask user before submitting the form on a MasterPage[/align]
[align=justify]In order to ask the user for a confirmation before submitting the form, you can either use code behind or can use simple mark up as shown below:[/align]
[align=justify]Declare a Button control that causes postback and write the following code in MasterPage.master.cs or .vb[/align]
C#
protected void Page_Load(object sender, EventArgs e)
{
string myScript = @"<script type='text/javascript'>
function askBeforeSubmit() {
var msg = 'Are you sure?';
return confirm(msg);
}
</script>";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MakeSure", myScript);
form1.Attributes.Add("onsubmit", "return askBeforeSubmit();");
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim myScript As String = "<script type='text/javascript'>" & ControlChars.CrLf & " function askBeforeSubmit() {" & ControlChars.CrLf & " var msg = 'Are you sure?';" & ControlChars.CrLf & " return confirm(msg);" & ControlChars.CrLf & " }" & ControlChars.CrLf & " </script>"
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "MakeSure", myScript)
form1.Attributes.Add("onsubmit", "return askBeforeSubmit();")
End Sub
[align=justify]If you want to avoid a code-behind approach, you can ask the user for a confirmation by using the OnClientClick() on the Submit button[/align]
<asp:Button ID="btnMaster" runat="server" Text="Button"
OnClientClick="return confirm('Are you sure?');"/>
[align=justify]These were some common scenarios and their solutions when using JavaScript on MasterPages. In the next article, we will see how to use JavaScript in Content Pages. Update: Part II of this article can be read over here Calling JavaScript from ASP.NET Master Page and Content Pages - Part II[/align]
[align=justify]I hope you liked the article and I thank you for viewing it.[/align]
[align=justify]Update: Part II of this article can be read over here Calling JavaScript from ASP.NET Master Page and Content Pages - Part II[/align]
[align=justify]Call JavaScript From Master Page[/align]
[align=justify]You can call an existing JavaScript function from a Master Page or can create one on the fly. Here are some common scenarios: [/align]
[align=justify]1. Create a JavaScript function on the fly and call the JavaScript function in the MasterPage Page_Load() event[/align]
[align=justify]C#[/align]
protected void Page_Load(object sender, EventArgs e)
{
string someScript = "";
someScript = "<script language='javascript'>alert('Called from CodeBehind');</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "onload", someScript);
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim someScript As String = ""
someScript = "<script language='javascript'>alert('Called from CodeBehind');</script>"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "onload", someScript)
End Sub
[align=justify][/align]
[align=justify]The Page.ClientScript.RegisterStartupScript() allows you to emit client-side script blocks from code behind. More info can be found over here http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerstartupscript.aspx[/align] [align=justify]2. Call an existing JavaScript function on MasterPage Page_Load() event[/align]
[align=justify]Let us assume you have an existing JavaScript function declared in between the <head> tags, then here’s how to call that function from Page_Load()[/align]
<head runat="server">
<title></title>
<script type="text/javascript">
function invokeMeMaster() {
alert('I was invoked from Master');
}
</script>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.ClientScript.IsStartupScriptRegistered("alert"))
{
Page.ClientScript.RegisterStartupScript
(this.GetType(), "alert", "invokeMeMaster();", true);
}
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (Not Page.ClientScript.IsStartupScriptRegistered("alert")) Then
Page.ClientScript.RegisterStartupScript(Me.GetType(), "alert", "invokeMeMaster();", True)
End If
End Sub
3. Call JavaScript function from MasterPage on Button click
If you want to call a JavaScript function on a Button click, then here’s how to do so:
<head runat="server">
<title></title>
<script type="text/javascript">
function invokeMeMaster() {
alert('I was invoked from Masterdotnetcurry');
}
</script>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
In the <body> tag, add a Button and use the OnClientClick to call this function
<asp:Button ID="btnMaster" runat="server" Text="Button" OnClientClick="return invokeMeMaster();"/>
[align=justify]The OnClientClick() is called before the postback occurs. This gives us a place to check for some condition and cancel the submit if the condition is not satisfied. We will see an example in Tip 6.[/align]
[align=justify]4. Access a control on the MasterPage using JavaScript[/align]
[align=justify]If you have a control on the MasterPage and need to access it using JavaScript, then here’s how to do so. In this sample, we will test the length of the TextBox to see if there are 5 or more letters. If the number of letters is less than 5, the form submit will be cancelled.[/align]
[align=justify]Add a TextBox and a Button control in the MasterPage (outside the ContentPlaceHolder) as shown below[/align]
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="panelMaster" GroupingText="MasterPage controls" runat="server">
<asp:TextBox ID="txtMaster" runat="server"></asp:TextBox>
<asp:Button ID="btnMaster" runat="server" Text="Button" OnClientClick="return accessMasterControl();" />
<br />
</asp:Panel>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
In the <head> element of the MasterPage, add the following code:
<head runat="server">
<title></title>
<script type="text/javascript">
function accessMasterControl() {
if (document.getElementById('<%=txtMaster.ClientID%>').value.length <= 5) {
alert('Minimum 5 characters required')
return false;
}
else { return true;}
}
</script>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
5. Access a control on the Content Page from a MasterPage using JavaScript
If you have a control on the Content Page which has to be accessed in the MasterPage using JavaScript, then here’s how to do so:
On the Content Page, create a TextBox as shown below :
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:Panel ID="panelContent" GroupingText="ContentPage Controls" runat="server">
<asp:TextBox ID="txtContent" runat="server"></asp:TextBox>
</asp:Panel>
</asp:Content>
Now access and populate the TextBox ‘txtContent’ from the MasterPage
<head runat="server">
<title></title>
<script type="text/javascript">
function accessControlContentPage() {
var txtCont = document.getElementById('<%= Page.Master.FindControl("ContentPlaceHolder1").FindControl("txtContent").ClientID %>');
txtCont.value = "I got populated using Master Page";
}
</script>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
[align=justify]6. Ask user before submitting the form on a MasterPage[/align]
[align=justify]In order to ask the user for a confirmation before submitting the form, you can either use code behind or can use simple mark up as shown below:[/align]
[align=justify]Declare a Button control that causes postback and write the following code in MasterPage.master.cs or .vb[/align]
C#
protected void Page_Load(object sender, EventArgs e)
{
string myScript = @"<script type='text/javascript'>
function askBeforeSubmit() {
var msg = 'Are you sure?';
return confirm(msg);
}
</script>";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MakeSure", myScript);
form1.Attributes.Add("onsubmit", "return askBeforeSubmit();");
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim myScript As String = "<script type='text/javascript'>" & ControlChars.CrLf & " function askBeforeSubmit() {" & ControlChars.CrLf & " var msg = 'Are you sure?';" & ControlChars.CrLf & " return confirm(msg);" & ControlChars.CrLf & " }" & ControlChars.CrLf & " </script>"
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "MakeSure", myScript)
form1.Attributes.Add("onsubmit", "return askBeforeSubmit();")
End Sub
[align=justify]If you want to avoid a code-behind approach, you can ask the user for a confirmation by using the OnClientClick() on the Submit button[/align]
<asp:Button ID="btnMaster" runat="server" Text="Button"
OnClientClick="return confirm('Are you sure?');"/>
[align=justify]These were some common scenarios and their solutions when using JavaScript on MasterPages. In the next article, we will see how to use JavaScript in Content Pages. Update: Part II of this article can be read over here Calling JavaScript from ASP.NET Master Page and Content Pages - Part II[/align]
[align=justify]I hope you liked the article and I thank you for viewing it.[/align]
相关文章推荐
- 海洋工作室——网站建设专家:Calling JavaScript from ASP.NET Master Page and Content Pages - Part II
- 海洋工作室——网站建设专家:Events in ASP.NET Master and Content Pages
- Calling JavaScript from ASP.NET Master Page and Content Pages
- 海洋工作室——网站建设专家:【原】在线订餐系统,可商业化!订单系统共享啦!!应用技术: AJAX, LINQ, MASTERPAGE, ASP.NET
- 海洋工作室——网站建设专家:【原】在线订餐系统,可商业化!订单系统共享啦!!应用技术: AJAX, LINQ, MASTERPAGE, ASP.NET
- 海洋工作室——网站建设专家:ASP.NET: How to Convert Your Site To A MasterPage Site in 3 Steps
- 海洋工作室——网站建设专家:jQuery-Ui Tabs and Asp.net MVC
- 海洋工作室——网站建设专家:Creating Multi-Level Navigational Menu with the ASP.NET Repeater Control and CSS Styles
- 海洋工作室——网站建设专家:How To: Create an ASP.NET AJAX Style Folder Explorer
- Events in ASP.NET Master and Content Pages
- 海洋工作室——网站建设专家:VS.NET - ASP.NET -ToolTip per node in ASP.NET Treeview control
- 海洋工作室——网站建设专家:如何在IIS6.0中部署asp.net mvc程序
- 完美解决Asp.Net的MasterPage中添加JavaScript路径问题
- Using ASP.NET and jQuery to Pass Multiple Values from a GridView to Another Page
- ASP.NET中Master Page和Content Page里的事件处理顺序
- Working with Data in ASP.NET 2.0 :: Master Pages and Site Navigation
- Embed client-side JavaScript in an ASP.NET 1.1 web page from server side code
- ASP.NET 2.0 MasterPages and FindControl()
- 完美解决Asp.Net的MasterPage中添加JavaScript路径问题
- ASP.NET MVC- VIEW Creating Page Layouts with View Master Pages Part 4