Enhancing ASP.NET Pages with JavaScript
by Matthew MacDonald, coauthor of ASP.NET in a Nutshell, 2nd Edition09/15/2003
ASP.NET is a server-based platform, which means the code you write executes on the web server instead of in the client's browser. This approach ensures that your code is kept secure from prying eyes, and it sidesteps most browser-compatibility issues. However, it also introduces some unavoidable limitations.
For example, the ASP.NET web page model doesn't provide any way to react to events, such as a user's mouse movements. In this case, the overhead of sending the page back to the server after every mouse movement would make the web page unworkably slow. Similarly, because your code can't interact directly with the browser, it can't display pop-up windows or manage multiple frames in a frameset in the same way a snippet of client-side JavaScript could.
To compensate for these limitations, ASP.NET developers often need to mix a little JavaScript code into their ASP.NET web pages. This is most commonly the case with custom controls. For example, many menu controls allow the user to browse through multiple menu levels without forcing the page to be posted back to the server every time a new level is shown. (You can find sample menu controls at Microsoft's community site.) Similar techniques are used to ensure that other controls remain rich and responsive, without requiring any work from the web server.
|
Related Reading
ASP.NET in a Nutshell |
In this article, we'll consider three common tasks that require JavaScript but aren't specific to custom controls. You can use these tricks to quickly solve problems that have no native .NET solution. But first, let's look at what you need to do to use JavaScript in an ASP.NET page.
Inserting JavaScript into an ASP.NET Page
To use JavaScript in an ASP.NET page, you first need to take two steps:
- Define the script block that contains the JavaScript function. You can add this directly to the HTML of the page, but it is usually more flexible to assign the JavaScript code to a string variable and insert it into the rendered page programmatically.
- Insert the script block programmatically. To do this, use either the
Page.RegisterStartupScript()or thePage.RegisterClientScriptBlock()method. In the first case, the JavaScript code will execute immediately the next time the page is posted back. In the latter case, the JavaScript code will not execute unless you connect the client-side event of another control to the JavaScript function. In this article, we'll use the first approach.
The next three sections demonstrate this technique.
- Showing a Pop-Up Window
Pop-up windows, often used for advertisements and promotions, are a hallmark of the Internet. But ASP.NET doesn't provide any mechanism for showing pop-up windows, because your code can't interact directly with the client's browser. The only solution is to use JavaScript, which provides the useful
Thewindow.open()function.window.open()function requires three parameters:- The link for the new page.
- The frame name of the window.
- A comma-separated string of attributes that will configure the style and size of the pop-up window. These can include the
heightandwidthattributes (with pixel values); thetoolbar,menuBar, andscrollbarattributes (set toyesorno, depending on whether you want to display these elements); and theresizableattribute (set toyesorno, depending on whether you want a fixed or resizable window border).
The following C# code defines the JavaScript code for showing the PopUp.aspx web page in a new window, and registers it to execute immediately upon the page being posted back the next time.
string popupScript = "<script language='javascript'>" + "window.open('PopUp.aspx', 'CustomPopUp', " + "'width=200, height=200, menubar=yes, resizable=no')" + "</script>"; Page.RegisterStartupScript("PopupScript", popupScript);In VB .NET, the code is virtually identical:
Dim popupScript As String = "<script language='javascript'>" & _ "window.open('PopUp.aspx', 'CustomPopUp', " & _ "'width=200, height=200, menubar=yes, resizable=no')" & _ "</script>" Page.RegisterStartupScript("PopupScript", popupScript)You can use this code in any event handler. For example, you might want the window to appear when the page first loads, or after the user clicks a button or performs another action. In any case, the pop-up window will only appear the next time the page is returned to the user. If you want it to reappear the next time the user takes an action, you'll need to create and register the script block again.
Note that when the script block is added to the page, it's identified with a descriptive name (in this case, "PopupScript"). If you add a script block with the same name multiple times, it will only be added to the page once.
- Changing Control Focus
The ASP.NET web controls provide a
TabIndexproperty, but this property only applies to Internet Explorer and can't be used to programmatically set the focus to a control of your choice. To perform this task, you'll need the help of some JavaScript code. In this case, you need to find the JavaScript object that corresponds to the control, and call itsfocus()method.The easiest way to handle this task is to create a function that accepts a control, extracts its client-side ID, and uses it to generate the JavaScript function required to set the focus to that control. You can then register this function so it will set the focus the next time the next time the page is sent to the user.
Here's the function you will need in C#:
private void SetFocus(Control ctrl) { // Define the JavaScript function for the specified control. string focusScript = "<script language='javascript'>" + "document.getElementById('" + ctrl.ClientID + "').focus();</script>"; // Add the JavaScript code to the page. Page.RegisterStartupScript("FocusScript", focusScript); }Here's the same function rewritten for VB .NET:
Private Sub SetFocus(ByVal ctrl As Control) ' Define the JavaScript function for the specified control. Dim focusScript As String = "<script language='javascript'>" & _ "document.getElementById('" + ctrl.ClientID & _ "').focus();</script>" ' Add the JavaScript code to the page. Page.RegisterStartupScript("FocusScript", focusScript) End SubYou can now call the custom
SetFocus()function from any event handler to change the control focus as needed:SetFocus(myTextBox);Remember, the focus change won't take effect until the page is rendered and sent back to the browser.
- Handling Frame Navigation
Frames allow you to display more than one HTML document in the same browser window. In the case of a site with a navigational menu, you could split the page vertically into two frames. The frame on the left would contain the navigation control, while the frame on the right would show the selected content. (For more information about frames, refer to this HTML Frames tutorial or this Web Authoring FAQ.)
Because frames only exist on the client side, it's a little more work to manipulate them in your ASP.NET code. You need to explicitly select the frame you want to modify, and then assign a new location (URL) to it. The following VB .NET code snippet registers the JavaScript coded needed to change frame 1 to a new page. You can assume that this code will run in the page inside of frame 0.
Dim url As String = "NewPage.aspx" ' Use JavaScript to trigger the redirect in the other window. Dim frameScript As String = "<script language='javascript'>" & _ "window.parent.frames(1).location='" & Url & "';</script>" Page.RegisterStartupScript("FrameScript", frameScript)The C# code is virtually identical:
string url = "NewPage.aspx"; // Use JavaScript to trigger the redirect in the other window. string frameScript = "<script language='javascript'>" + "window.parent.frames(1).location='" + url + "';</script>" Page.RegisterStartupScript("FrameScript", frameScript);
Summary
A sprinkling of JavaScript code can enhance the reach and responsiveness of your ASP.NET web pages. Best of all, you don't need to sacrifice ASP.NET's secure, server- based model for the bulk of your coding; just fill in the gaps with a little dash of client-side magic.
Matthew MacDonald is a developer, author, and educator in all things Visual Basic and .NET. He's worked with Visual Basic and ASP since their initial versions, and written over a dozen books on the subject, including The Book of VB .NET (No Starch Press) and Visual Basic 2005: A Developer's Notebook (O'Reilly). His web site is http://www.prosetech.com/.
O'Reilly & Associates recently released (August 2003) ASP.NET in a Nutshell, 2nd Edition.
Sample Chapter 6, "User Controls and Custom Server Controls," is available free online.
You can also look at the Table of Contents, the Index, and the full description of the book.
For more information, or to order the book, click here.
Return to ONDotnet.com
Showing messages 1 through 41 of 41.
-
how we call a javascript in the coding
2008-11-15 02:59:08 hundya [View]
-
how we call a javascript in the coding
2008-11-15 03:21:32 hundya [View]
how to use a printmethod
-
Click Cancel Button (asp dot net with c#)
2008-07-18 08:50:21 HopeForBest [View]
I need help....
I have a click button, after click on it, it should go on previous page (in asp dot net with c#))
-
Dynamic youtube plugin in asp.net with c#
2008-04-24 06:40:30 Keisham [View]
I have embedded the youtube plugin in the asp.net using
<embed id="playvideo" src="http://www.youtube.com/v/Y8pAhZUN16c&feature=bz301" pluginspage="application/x-shockwave-flash" width="425" height="355"></embed>.
I want to change the video dynamically, by changing the src=. In Javascript it was quite straightforward.
How can we dynamically update the src= in asp.net using c#. The difficulty that I face is that <embed> is not a asp.net object its HTML, so it is not recognized in the server. How can I go about with this.
golden helping hand needed.
Thanks,
Keisham
-
Dynamic youtube plugin in asp.net with c#
2008-04-25 06:33:47 Keisham [View]
I have found the solution to this, Am posting this to help someone who faces similar problem.
you got to create a function say
public void passurl(string url)
{
"<script language=javascript>" +
"document.getElementById('elementID').src='"+ url+ "'; </script>";
page.RegisterStartupScript("put the params here"};
}
call this on some event.
Cheers,
Keisham
-
how to use hoverovver by javascript.
2008-01-10 17:46:16 aammiz [View]
1)if i have button and want to have hoverover affect how i can achive that.
2) Also, what would be the code to handle several buttons or label control by css file?
Thanks
-
how to hide controls using javascript
2008-01-10 17:42:59 aammiz [View]
hi,
I have a form where I have a submit button sever and a label, which are server controls.
When the user clicks on the button, I want to hide those controls along with other process. The other process take several minutes and I get a response in few minutes from the server. So I want to hide those controls by javascript as soon as the user clicks.
I could use the Button.Visible=false;
But this could happen after I get a response from the server, therefore not acceptable.
So any help??
-
Need help with popup box (lookup).
2007-08-26 05:25:53 yasinirshad [View]
I have a form with textbox. Besides this textbox i should have imagebutton / something which on clicking will open a popup window (lookup). This popup window will have UserId and Usernames (from db). So when the User selects one from this , the UserId should get selected in the textbox. How to do this? Please help. Can you please send me a sample of this type ..? Its very urgent.
Thanks lot..
-
Need help with popup box (lookup).
2007-09-21 01:15:43 sunithashukla [View]
In first page source code write code in Script as
<script type="text/javascript" language="javascript">
function getId(ControlId,UserName)
{
document.getElementById(ControlId).value = UserName;
}
</script>
......
and next go to .cs of same page and write code as
protected void Page_Load(object sender, EventArgs e)
{
lnkbt.OnClientClick = "window.open('GridView.aspx?ControlId=" + txtName.ClientID + "')";
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("<script>alert('Hai')</script>");
}
...........
Go to next page and write below code in source code as
<script type="text/javascript" language="javascript">
function getData(ControlId,UserName)
{
window.opener.getId(ControlId,UserName);
window.close();
}
</script>
................
next go to .cs of this page 2 and write code as
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId");
dt.Columns.Add("UserName");
dt.Columns.Add("Password");
dt.Columns.Add("EmailId");
dt.Rows.Add("1", "Ravi", "Ravi", "Ravi@gmail.com");
dt.Rows.Add("2", "Rama", "Rama", "Rama@gmail.com");
dt.Rows.Add("3", "Ramu", "Ramu", "Ramu@gmail.com");
dt.Rows.Add("4", "Rao", "Rao", "Rao@gmail.com");
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
LinkButton lnkSelect = (LinkButton)e.Row.FindControl("lnkselect");
if (e.Row.RowType == DataControlRowType.DataRow)
{
lnkSelect.OnClientClick = "getData('" + Request.QueryString["ControlId"].ToString() + "','" + e.Row.Cells[1].Text + "');";
//lnkSelect.OnClientClick = "test();";
}
}
}
..................
Actually in this senario when we run the program and click on a button it will redirect to other page with in the window ie a popup box.In this window if we click on any row of gridview column then this window 2 will close and id will display in page 1 at textbox.
I think so this is correct answer .
-
javascript
2007-06-04 20:09:55 RyanOng [View]
Hi i need some help here.
i got one asp windows page with a textbox and a button.When i click the button, a windows confirmation page with "yes" and "no" button will be generated. So if i click "yes", the textbox in the asp will appear "yes" and if i clicked "no",the textbox will appear "no".
Can anyone help me out???
Thanks alot.
-
validation in .ascx file
2007-05-10 02:17:04 banani [View]
i have one .aspx page,where i will use an user control.in that user control i am having two textboxes and one submit button.on submitting that button a mail will be send.now the question is that, is it possible to validate the 2 textbox controls and the button itself in the .ascx or .ascx.cs file using javascript?please reply soon.it's really very urgent.
-
hi
2007-04-16 23:58:56 muneiah [View]
HI All,
Please can any one help this one,
Where we use java script except validation in ASP.Net
Thanks,
Thulasi. -
hi
2007-09-21 04:21:06 sunithashukla [View]
if u want to run any event in client side then u have to use javascript.
for example if u want to run a timer control in client side then u have to use java script,
we can run the timer in server side also
-
i Want help in disabling images by enabling another image in the same screen
2007-03-28 06:48:59 AZEEZ [View]
i have one image that is the combination of some other images,Now the requirement is if one the images on the MainImage(i.e combination of some other images by arranging the images in particular positions)is clicked the remaining images should be disabled.this is to be done in javascript,so Please can you help me regarding this,
-
RegisterScript before Response.Redirect()
2007-01-15 00:48:25 SwethaSN [View]
Hi,
Can any one please tell me how to register the script just before invoking Response.Redirect()?
Thanks,
Swetha -
RegisterScript before Response.Redirect()
2007-01-15 03:15:07 SwethaSN [View]
I got to know how to register the script but the same logic does not work with NetScape & Firefox.
Code -
Page.RegisterStartupScript("onSubmit","<script>FireAlert('PPP');redirect();</script>");
This fires the alert & then navigates to next page & on browsing back again fires the alert followed by redirect(). So we need to incorporate a condition in redirect() method to avoid repetative calls.
But I am not finding a solution for NetScape & Firefox. Please let me know if anyone has come across such issues.
Thanks,
Swetha -
RegisterScript before Response.Redirect()
2007-11-15 03:53:37 niteensapkal [View]
Have u solve this problem i.e. alert , Response.Redirect and Back button..
Plese tell me it.. I am facing same problem.
-
I want help
2007-01-03 02:28:41 SanShark [View]
i m working on project where already used a user control. I want to change the visibility of that user control using JavaScript. How do i get id of that user control & where should i write my JavaScript -
I want help
2007-09-21 06:49:56 sunithashukla [View]
Go to that perticular Control of source code and place this
disabled="disabled".
I think so it matchs u
-
Customizing the cursor position in text box
2006-12-18 03:30:06 prvn [View]
How to set the cursor to a custom position(at any location the user wants) in a text box? Say, if we default a text box with some text(on a button click event) and we need to place the cursor at the end of the string in the text box.
The Java Script function textbox1.focus() places the cursor only at the first position. Is there any means to change the function by passing some parameters or something like that to achieve the above said problem.
Expecting your suggestions.
-
Thanx
2006-12-16 01:28:31 ArunSaini [View]
You article saved me from being fired.
Thanx again.
-
COOL!!
2006-12-09 21:07:07 My_head_hurts! [View]
I am writing an app that uses .asp to generate static pages.
you reference to "document.getElementById()" came in VERY handy.
I was writing a section from some used code that rotated images randomly on a certain time interval. The problem was that I needed to associate alt text and a link.
The text was no problem. The link, however, cost me a great deal of time. I was able to use that function to set the href on the anchor surrounding the image.
DUDE, YOU ROCK!
-
COOL!!
2006-12-09 21:06:48 My_head_hurts! [View]
I am writing an app that uses .asp to generate static pages.
you reference to "document.getElementById()" came in VERY handy.
I was writing a section from some used code that rotated images randomly on a certain time interval. The problem was that I needed to associate alt text and a link.
The text was no problem. The link, however, cost me a great deal of time. I was able to use that function to set the href on the anchor surrounding the image.
DUDE, YOU ROCK!
-
How to use C# string variable in JavaScript
2006-10-06 00:01:51 ManishKSingh [View]
I want to pass a string variable and show it in a alert box but i am not able to get the value from the string variable which i m passing from C# code.
Here is the function where i am doing the effort.Please suggests the solution.
private void PopUpMessege(string msg)
{
string popupScript = "<script language='javascript'>" +
"window.alert(msg);</script>";
Page.RegisterStartupScript("PopupScript", popupScript);
} -
How to use C# string variable in JavaScript
2006-10-22 01:54:53 ashraf_gawdat [View]
This must be working
private void PopUpMessege(string msg)
{
string popupScript = "<script language='javascript'>" +
"window.alert("+msg+");</script>";
Page.RegisterStartupScript("PopupScript", popupScript);
}
So you must add the variable (msg) as a variable not as a part of the string
-
can any one help me
2006-03-25 06:24:47 javascript11 [View]
how to use the value of the variable which is stored in by javascript in asp.net
-
Executing code-behind from javascript
2006-02-20 10:17:45 Crist3l [View]
I am using delphi for my project,but any type of code will be good.<br/>
So..this is my problem: I want to execute from a javascript function i have in a .aspx file, a function that i have in code-behind in a user control.What i have by now is :<br/>
__doPostBack('ucPeticionAlta$LinkButton1','')<br/>
The problem with this is that it gets executed only once....Second time itīs like the line is not there.<br/>
Thx. -
Executing code-behind from javascript
2006-02-20 10:18:56 Crist3l [View]
lol...no br tags...just ignore them..sorry
-
In asp.net how to Integrate an existing Java script
2005-11-27 23:42:43 lrTest1 [View]
<script language="JavaScript" src="../../Common/Html/atlas.js"></script>
<SCRIPT language="JavaScript">
var centerWidth = 486;
var centerHeight = 385;
var randTeeth = new Array();
randTeeth[0] = 13;
randTeeth[1] = 16;
randTeeth[2] = 17;
randTeeth[3] = 23;
function calcOpacity() {
xOff = event.clientX - getAbsoluteLeft(centerDiv) + 151;
yOff = event.clientY - getAbsoluteTop(centerDiv) + 88;
xFrac = xOff/centerWidth;
yFrac = yOff/centerHeight;
// window.status = "xOff, yOff ... xFrac, yFrac: (" + xOff + ", " + yOff + ") " + xFrac + ", " + yFrac;
photoFrac = Math.min(100, Math.max(0, (1.0 - yFrac)*100))
simulatedFrac = Math.min(100, Math.max(0, (1.0 - xFrac)*100));
photoImg.filters.item("DXImageTransform.Microsoft.Alpha").opacity = photoFrac;
simulatedImg.filters.item("DXImageTransform.Microsoft.Alpha").opacity = simulatedFrac;
}
function initSplashPage() {
initPage();
// CRAIG SUCKS BIG TIME !!!!!!!
// INSTEAD OF RELYING ON INITPAGE(), HE MAY AS WELL HARD CODE 'tn', SINCE ONLY '13' WILL WORK!!!
tn = 13;
if(tn == 13) { rNum = Math.random()*randTeeth.length;
tn = randTeeth[Math.floor(rNum)];
}
photoImg.src = "../../Data/tooth" + tn + "/misc/splashPhoto.jpg";
simulatedImg.src = "../../Data/tooth" + tn + "/misc/splashSimulated.jpg";
xrayImg.src = "../../Data/tooth" + tn + "/misc/splashXray.jpg";
document.onmousemove = calcOpacity; // put this in the init function so it doesn't execute until the page is loaded and the objects required exist
}
how to add this java Script to Asp.net -
In asp.net how to Integrate an existing Java script
2006-10-12 06:29:11 sreen1 [View]
-
Problem with Page.RegisterStartupScript
2005-03-23 22:45:28 vishalvishal [View]
Hi,
when you add javascript code to your page using Page.RegisterStartupScript and you redirect to some other page and now if you use browser's back button and come to the original page the script add get's executed automatically.
If i am showing a confirm and clicking "yes" button i redirect user to some other page through javascript's window.location.href='ABC.aspx'
and if i press browser's back button on ABC.aspx page i see the confirmation box on the previous page.
So is there any way that i can avoid this.
thnx.. -
Problem with Page.RegisterStartupScript
2006-06-27 04:35:50 ROCK007 [View]
Hi All,
Another same alike query. When we add a Page.RegisterStartupScript and try to browse to another page from the current page (where this javascript is written), we get a message saying "Do you really want to navigate from the current page?" since we have used window.BeforeUnload to halt when some values are changed. Even though we have clicked "Cancel" button to avoid going out of the page, it stays back but after clicking the "save" button it does not fires the "Button_Click" event handler. This Button click handler works with the normal case.
What should be done to drap the Button_Click event in such case?
ThanX
-
Problem with Page.RegisterStartupScript
2005-05-20 03:11:21 u [View]
set a flag for back and in main page check the flage if true? no action should be done.like this one
if(!Back)
page.RegisterStartupScript("name",name)
-
Frame Navigation
2004-07-30 11:52:07 SamCranford [View]
You can also use ASP.NET data binding to change the src of a frame, like this
In script block or code behind:
Public contentUrl as string = "main.aspx"
Private Sub Page_Load(<args not included)
If WhateverTest = True Then
contentUrl = "here.aspx"
End If
DataBind()
End Sub
In the html:
<frame src="<%# contentUrl %>" id="MainContent" name="MainContent" frameborder=no />
It works better than the Javascript redirect, which I was using before. It cause the default page to flash quickly before the redirect. It also caused the default page to perform all of its processing for nothing.
Thanks,
Sam
-
JavaScript for other ASP.NET
2004-01-03 16:33:08 anonymous2 [View]
-
JavaScript for other ASP.NET
2006-01-26 10:22:21 cbran [View]
I copied and pasted your example to open a window, and received error: string constants must end with a double quote.
The pop_window routine is called from an asp:button.
Here is your example:
Sub pop_window(Sender As Object, e As EventArgs)
Dim popupScript As String = "<script language='javascript'>" & _
"window.open('PopUp.aspx', 'CustomPopUp', " & _
"'width=200, height=200, menubar=yes, resizable=no')" & _
"</script>"
Page.RegisterStartupScript("PopupScript", popupScript)
End Sub
-
JavaScript for other ASP.NET
2006-06-08 09:40:10 SU [View]
Did you happen to resolve this issue. I am also getting the same error.
If you know what the cause and how to resolve this please share with me. Thanks in advance -
JavaScript for other ASP.NET
2006-02-06 02:40:35 mohanramkumar [View]
Hi this is mohan from photoninfotech.I am basically an mechanical engg i completed in 2005 and directly came to s/w field and now i am doing small tasks .I have a small problem with this i need some help from u,here i am using the javascript for coding and my question is
Actually i created a 3types of fileds
1)id
2)name
3}address
now the problem is that all these 3fields are in the same web page,what i required is i need to have the 3fields in another page like the login page i tried it using the pannel,tables and all but i could not get it,so can i please help me how can i get the 3fields in the same page. -
JavaScript for other ASP.NET
2006-02-20 10:12:49 Crist3l [View]
Response.Redirect("myPage.aspx?Id="+idField+"&Name="+nameField+"&Address="+addressField);
....from javascript:
location.href("here you put the same as above"); -
JavaScript for other ASP.NET
2007-01-21 23:16:47 samreet [View]
Well try....... -
JavaScript for other ASP.NET
2006-03-25 06:38:16 javascript11 [View]
can u please explain the code above as how it works please
i'm in bad need to use the variable used in script in asp.dot










My question is .In windows we have a printdialog tool but in asp.net we don't have a such tool.So how
we call the window.print in the application part.