javascript in content pages

B

bbawa1

Hi,

I have a master page and content page. In content page I have to
validate the text boxes for
name,address, phone number and email address etc. But as content pages
doersn't have html section not head or body section so, where I use
this java script in content page to validate the form.

Thanks
 
M

Mark Rae

I have a master page and content page. In content page I have to
validate the text boxes for
name,address, phone number and email address etc. But as content pages
doersn't have html section not head or body section so, where I use
this java script in content page to validate the form.

Anywhere you like - I usually put it at the very beginning of the content
page...
 
R

Ray Costanzo

Use the RegisterClientScriptBock method. Example:


--codebehind for somepage.cs, which uses a masterpage (although this doesn't
matter)

Page.aspx:
<input type="button" onclick="something();" value="click me" />

Page.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
Page.RegisterClientScriptBlock("uniqueString", "<script
type=\"text/javascript\">function something(){
alert('something'); }</script>");
}


Doing the Javascript construction in the .cs file can get annoying and
messy, so I will often put the javascript in the aspx (or ascx) file in a
literal control that I never display, but read the contents of, like so:

Page2.aspx:
<input type="button" onclick="somefunction();" value="clickme" />
<asp:Literal ID="litClientScript" runat="server" Visible="false">
<script type="text/javascript">
function somefunction() {
var x = 3;
var y = 9;
alert(x*y);
}
</script>
</asp:Literal>


Page2.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
Page.RegisterClientScriptBlock("clientScript", litClientScript.Text);
}

Ray at work
 
R

Ray Costanzo

Mark is correct that this will work. You can put javascript anywhere you
like. Purists would advise against it, but in reality, it'll still work
just the same. The one problem you can run into is the way that javascript
is loaded and executed at the same time, so if you call something that
appears higher up in the page, you'll get an error in the browser. Example:

<body>
<script type="text/javascript">
somefunc('first call'); //this will fail here
</script>

<script type="text/javascript">
function somefunc(s) {
alert(s);
}
</script>

<script type="text/javascript">
somefunc('second call'); //this will work
</script>
</body>



Ray at work
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top