how to call a javascript function from content page which was declared in master page?
this is my master page
<%
@ Master Language="VB" CodeFile="MasterPage.master.vb" Inherits="MasterPage" %><
html xmlns="http://www.w3.org/1999/xhtml" ><
head runat="server"> <title>calendar</title><
meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"><
meta name="CODE_LANGUAGE" content="Visual Basic .NET 7.1"><
meta name="vs_defaultClientScript" content="JavaScript"><
meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"><
script language="JavaScript" src="calendar2.js"></script></
head><
body> <form id="Form1" method="post" runat="server"> <table > <tr><td width= 700 bgcolor="dimgrey"> <div> <asp:contentplaceholder id="ContentPlaceHolder1" runat="server"> </asp:contentplaceholder> </div> </td></tr></table> </form> <script language="javascript">var
cal1 = new calendar2(document.forms['Form1'].TextBox1);</
script></
body></
html>********* this is my content page************
<%
@ Page Language="VB" MasterPageFile ="~/MasterPage.master" AutoEventWireup="false" CodeFile="Calender.aspx.vb" Inherits="Calender" %><
asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"><
table><tr><td><
p><
a href=cal1.popup();">Click here</a></
p><
asp:TextBox id="TextBox1" runat="server"></asp:TextBox></td></tr><
tr><td><asp:LinkButton id="lnkHome" runat="server">Home</asp:LinkButton></
td></tr></table></
asp:content>how to call href=cal1.popup();" function from content page. this is a calender control i need to add in most of the pages in my application
please help me friends.
所有回覆
Hi,
Use Scripting Generator methods.
<
asp:Content ID="Content3" ContentPlaceHolderID="Content" Runat="Server" ><input type="text" name="Message" runat="server">
<
input name="TextBox1" type="button" runat="server" value="ClickMe" onclick="DoClick()"></
asp:Content>
protected
void Page_Load(object sender, EventArgs e){
// Define the name and type of the client scripts on the page.
String csname = "ButtonClickScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the client script is already registered.
if (!cs.IsClientScriptBlockRegistered(cstype, csname)){
StringBuilder cstext2 = new StringBuilder();
cstext2.Append("<script type='text/javascript'> function DoClick() {");
cstext2.Append("document.forms[0].Message.value='Text from client script.'} </");
cstext2.Append("script>");
cs.RegisterClientScriptBlock(cstype, csname, cstext2.ToString(), false);
}
}
Regards,
Omer kamal
------->
I'm new to asp.net, but what about putting this in the Page_Load event of the master page:
Response.Write("<SCRIPT LANGUAGE='JavaScript' src='" & Server.MapPath("~/Scripts/filename.js") & "'></SCRIPT>")
are there any problems to doing this?
also, did I misunderstand the question?
- Hi mors,
you can call the javascript within the page_prerender()...... event of your Masterpage. I had overcome with the same problem adding the Calendar to a content page... So i added that javascript within the page_prerender() event and it works fine for me. Try it.. If you need more help with that just let me know it.
C#_Worker - Thanks c# - do I add it the same way that I wrote or do I do it with other vb/c# functions?
Including JavaScript codes,
eg: An ASP textbox control with the ID="targetDate" and onClick or onClientClick we want to call a JavaScript function(Displaying a calendar within a Div),
OnClick="displayCalendar(document.forms[0].targetDate",'mm/dd/yyyy',this)"We cannot pass the control name like this. it's giving the JavaScript error.
so there is a way we used to resolve that problem(in C#),
protected void Page_PreRender(object sender, EventArgs e)
{
this.targetDate.Attributes["onclick"] = "displayCalendar(" + this.targetDate.ClientID + ",'mm/dd/yyyy',this)";
}That is what I did exactly ....Hope you got the idea... If you have more questions let me know it.. I will reply to you tonight(Canada).One last thing you have to add the <script> file within the Masterpage(.aspx page) as normal.
NOTE: Even I added same thing for OnFocus of the text box as well.
Thanks again. Here's what I did:
in the master page Page_Load event I have:
Page.ClientScript.RegisterStartupScript(Me.GetType(), "commonjsfile", "<SCRIPT LANGUAGE='JavaScript' src='" & Request.ApplicationPath & "/Scripts/Js/Javascriptfile.js" & "'></script>")
I did have it just saying response.write("<script src...">) but I guess this is the wrong way to do it.
My questions:
1. like I said above, i put that script thing in the master's page_load event - should I put it in the prerender event?
2. In order to add/set attributes to elements(like onClick), I was putting them in the Page_Load event. Is the better place in the Page_PreRender event or the individual elements Init() event or ???? - and why?
3. If I want to set something in the Style attribute, can I just say attributes("style") = "display:none;" or do I need to say attributes("style") &= "display:none:" to add to the style? - note: I just tried a couple of things: if I just say = instead of &=, then the other style attributes aren't applied to the element. However, by using &= to add to the style, when this page is postedback, then thst style of the element has multiple entries ex: "display:none;display:none". So I guess the thing to do is check if "display:none" is in the style attribute before adding it. correct?
I'm new to asp (much less asp.net) - i don't even code in vb or c#, but it's not that bad. I code in foxpro of all things lol (and yes i'm using connections to vfp tables instead of sql server or access)
Here is what I do in my page.
TestForm.aspx
<%
@ Page Language="C#" EnableEventValidation="true" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="TestForm.aspx.cs" Inherits="TestForm" Title="Test Form" %><
script language="javascript"><!--
var
cal1 = new CalendarPopup("date1"); // --></
script><form>
<
asp:TextBox ID="txtDate" runat="server" MaxLength="10" Width="80px"></asp:TextBox> <a id="A1" href="#" onClick="cal1.select(ctl00_ContentPlaceHolder1_txtDate,'imgCal','M/d/yyyy'); return false;" runat="server"><img src="../Calendar/img/cal.gif" id="imgCal" name="imgCal" runat="server" border="0" /></a></form>
Conclusion: if you are using the masterpage, the name/ID of the textbox or other input field will change on the client side from 'txtDate' to 'ctl00_ContentPlaceHolder1_txtDate'. So to check the name/id just launch the page and click to view the source code.
Hope this help
- Thanks...This blog was really useful!!!
- Hi GoodGuy,
I know as you posted in blog "ctl00_ContentPlaceHolder1_txtDate" works fine... But that's not the right way to do it. So try to find something right... Think about a situation like more than 50 controls... are you going to do the same thing? - you may use document.getElementByID('<%=yourControl.ClientID%>') to get the real ID of the control when it is rendered
Hai,
Thank you, you solved my problem, Its Working fine.
Thank you
But what if I want to pass yourControl as a parameter to the javascript function ? I want to make it work something like this...
Something like...
function test(x){
alert(document.getElementById("<%=x.ClientID%>").value);
}
But the above code throws error...want the parameter 'x' to be replaced by my control name.
Any help would be really appreciated.
Thanks
- webchetan
Can you send that code to me once?
var
zipValue=document.getElementById("<%= txtZipCode.ClientID %>").value;Right now i am using like this. Please tell me in future we didnt get any problem r not.
Tied popUpCalendar.aspx page with IMG HyperLink(The image was a small calendar) located on a contentpage
<td align="left" style="height: 26px"> <asp:TextBox ID="txtDate" Runat="server" AutoPostBack="True" ReadOnly="True" Width="93px" /> </td><
td align="center" style="height: 26px"> <a href="javascript:;" onclick="window.open('popUpCalendar.aspx?strTextBoxId=txtDate&strFormId=frmMainCommLog','cal','width=250,height=225,left=270,top=180')"> <img src="images/calendar.gif" border="0" id="imgCalendar" ></a> </td>I had to hard code the element ID on the rendered HTML page.
My txtDate control ID now = 'aspnetForm.ctl00$ContentPlaceHolder1$txtDate'
It has do with the ASP ContentPlaceHolder and MasterPage inherting INamingCotainer, which uniquely idenifies your controls on the rendered html, also renameing your form name. I also think there is a better way to code the rendered controlID or turn off INamingContainer?
<%
@ Page Language="VB" AutoEventWireup="false" CodeFile="popUpCalendar.aspx.vb" Inherits="popUpCalendar" %><!
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>Untitled Page</title></
head><
body> <form id="frmCalendar" method="post" runat="server"> <div> <asp:Calendar ID="calDate" Runat="server" BackColor="White" BorderColor="#3366CC" BorderWidth="1px" CellPadding="1" DayNameFormat="Shortest" Font-Names="Verdana" Font-Size="8pt" ForeColor="#003399" Height="200px" Width="220px" > <SelectedDayStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" /> <TodayDayStyle BackColor="#99CCCC" ForeColor="White" /> <SelectorStyle BackColor="#99CCCC" ForeColor="#336666" /> <WeekendDayStyle BackColor="#CCCCFF" /> <OtherMonthDayStyle ForeColor="#999999" /> <NextPrevStyle Font-Size="8pt" ForeColor="#CCCCFF" /> <DayHeaderStyle BackColor="#99CCCC" ForeColor="#336666" Height="1px" /> <TitleStyle BackColor="#003399" BorderColor="#3366CC" BorderWidth="1px" Font-Bold="True" Font-Size="10pt" ForeColor="#CCCCFF" Height="25px" /> </asp:Calendar> <input type="hidden" id="strFormId" runat="server" /> <input type="hidden" id="strCtrlId" runat="server" /> </div> </form></
body></
html>Partial
Class popUpCalendar Inherits System.Web.UI.Page Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.LoadstrFormId.Value = Request.QueryString(
"strTextBoxId").ToString()strCtrlId.Value = Request.QueryString(
"strFormId").ToString() End Sub Protected Sub calDate_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles calDate.SelectionChanged 'Dim script literal strScript Dim strScript As String = "<script>window.opener.document.aspnetForm.ctl00$ContentPlaceHolder1$txtDate.value = '"strScript += calDate.SelectedDate.ToString(
"MM/dd/yyyy")strScript +=
"';self.close()"strScript +=
"</" + "script>" 'Registers the client script with the Page object using a type, key, and script literal.Page.ClientScript.RegisterClientScriptBlock(
Me.GetType(), "PopulateOwnerWindowTxtDateScript", strScript) End Sub End ClassIt seems like any type of Post Content Page Rendering javascript dom accesses has to take into account this renaming convention. Is there a way to change the elementID back to their original ControlID. Or do I use a FindControl() function, after the page is loaded. Any help here would be appreciated.
Not sure if anyone will have the patience to help me as I am at the point where I can get some basic stuff to work but don't understand enough about it all to tweak it.
Using VWD 2005 Express I have a simple (AJAX enabled) web page that refines the list of results from a database query in a GridView as you type into a textbox (i.e. after each keypress - javascript OnKeyUp). When I try to implement this in a MasterPage the script no longer works. I understand that this is because the ID of the TextBox and other items are changed by virtue of the content page being rendered within the ContentPlaceHolder on the MasterPage.
The functioning page (no MasterPage) is basically:
==============Default.aspx========================
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Find Stuff</title>
<script language="javascript">
function OnKeyUp()
{
document.body.setActive();
document.body.focus();
window.event.srcElement.focus();
}
function SetCursorToTextEnd(textControlID)
{
var text = document.getElementById(textControlID);
if (text != null && text.value.length > 0)
{
if (text.createTextRange)
{
var FieldRange = text.createTextRange();
FieldRange.moveStart('character', text.value.length);
FieldRange.collapse();
FieldRange.select();
}
}
}
</
script></
head><
body><form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" >
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="FindStuff" runat="server" >
<ContentTemplate>
<asp:TextBox ID="SearchFor" runat="server" AutoPostBack="True"
OnTextChanged="SearchFor_TextChanged" >%
</asp:TextBox>
<br />
<asp:GridView ID="GridView1" runat="server" ..........>
<Columns>
..................
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:xxxxxxxxxxx%>"
SelectCommand="SELECT .......... WHERE ([customer_name] LIKE '%' + @customer_name + '%')">
<SelectParameters>
<asp:ControlParameter ControlID="SearchFor" Name="customer_name"
PropertyName="Text" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="SearchFor" />
</Triggers>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
---------------------------Default.aspx.cs-----------------------------
using
System;using
System.Data;using
System.Configuration;using
System.Web;using
System.Web.Security;using
System.Web.UI;using
System.Web.UI.WebControls;using
System.Web.UI.WebControls.WebParts;using
System.Web.UI.HtmlControls;public
partial class _Default : System.Web.UI.Page{
protected void Page_Load(object sender, EventArgs e)
{
SearchFor.Attributes.Add("onkeyup", "OnKeyUp();");
SearchFor.Attributes.Add("onfocus", "SetCursorToTextEnd(this.id);");
SetFocus(SearchFor);
}
protected void SearchFor_TextChanged(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock((Control)sender, sender.GetType(), "MyKey",
"WebForm_AutoFocus('" + SearchFor + "');", true);
}
}
==================================================================
Once a MasterPage is included/referenced, the TextBox ID "SearchFor" will become something like "ctl00_ContentPlaceHolder1_SearchFor". What can I do to make the javascript work AND make it dynamic so that it will work with other TextBoxes on other pages? How do I place the script in a file ("~/myscripts/keyup.js") and reference it in the MasterPage so that it works with other pages that are not in the root folder?
Thanks
Problem:
how to access the value in a html textbox present inside a gridview of an aspx page which inherits a master page?
i have written a java script to find sum of 2 numbers present in html textbox control with in a grid view.
my java script triggers on onblur event of HTML textbox placed in a gridview.i tried it out with a alert box showing "hello".
but i cant alert the value present in that html textbox . without master page we use
document.form1.yourcontrol.value to access the textbox value.but
how to access the value OF a html textbox present inside a gridview of an aspx page which inherits a master page?
i have placed my aspx and master page source code.
this code triggers my java script
default.aspx:
<%
@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Title="Untitled Page" %><
asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"></
asp:Content><
asp:Content ID="Content2" runat="server" contentplaceholderid="ContentPlaceHolder1"> <script type="text/javascript" language="javascript"> function calc(){
var num1=S1.n1.value; var num2=S1.n2.value;alert(num1);
var num3=num1+num2;alert(num3);
}
</script> <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataSourceID="AccessDataSource1"> <Columns> <asp:boundfield DataField="Code" HeaderText="Code" SortExpression="Code"> </asp:boundfield> <asp:boundfield DataField="CodeDescription" HeaderText="CodeDescription" SortExpression="CodeDescription"></asp:boundfield> <asp:boundfield DataField="CodeType" HeaderText="CodeType" SortExpression="CodeType"></asp:boundfield> <asp:TemplateField> <ItemTemplate> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> </ItemTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <input type="text" id="n1" name="n1" runat="server" /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <input type="text" id="n2" name="n2" onblur="javascript:calc()" /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <input type="text" id="n3" name="n3" runat="server" /> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> <asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/NCM.mdb" SelectCommand="SELECT * FROM [Code]"> </asp:AccessDataSource></
asp:Content>masterpage.master:
<%
@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %><!
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>Untitled Page</title> <asp:ContentPlaceHolder id="head" runat="server"> </asp:ContentPlaceHolder> <script language="javascript" type="text/javascript"> function calc(){
var num1=document.form1.n1.value; var num2=document.form1.n2.value; var num3=num1+num2;document.form1.n3.Value=num3;
}
</script></
head><
body> <form id="S1" runat="server"> <div> <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server"> </asp:ContentPlaceHolder> </div> </form></
body></
html>THANKS IN ADVANCE....
Thanks A tones....... Omer kamal This worked for me.Hello,
I am new to Javascript and ASP .NET 2.0 and I have a situation here. It is very much similar to the example you have given here but it is not a textbox but a CheckBox in the Grid. I am using MasterPages and in one of my contentpage I have a gridview which contains a checkbox templatefield. I want to make a Javascript function call on the checkedchange of any of the checkbox rows (in my case all the records in the gridview are basically info for documents) hence on checking a document (in the grid) I need to increment the count of the docs(rows in the grid)displayed in a textbox in the same content page. I am having issues wiring up the events to the Javascript using content page and master page. Please let me know what can be done in this scenario. My checkbox is an Asp .net checkbox and the textbox whixh displaying the count is an asp .net control as well. I am closing in on a deadline for my project and desperate at the moment to figure out a way without making server roundtrips (postbacks). I would greatly appreciate all the help.
Thanks in Advance..
Smitha
- 已提議為解答Dalsoglio Tuesday, 24 June, 2008 22:42
- webchetan said:
But what if I want to pass yourControl as a parameter to the javascript function ? I want to make it work something like this...
Something like...
function test(x){
alert(document.getElementById("<%=x.ClientID%>").value);
}
But the above code throws error...want the parameter 'x' to be replaced by my control name.
Any help would be really appreciated.
Thanks
- webchetan
the easiest way to do this is as follows:
function test(x){
alert(x.value);
}
<asp:TextBox id="abc" onchange="javascript:test(this)" runat="server" />
Hope this helps.

