?
Solved

ASP.NET/VB - Call method on key press - Need Smart One

Posted on 2009-12-20
11
Medium Priority
?
692 Views
Last Modified: 2012-06-21
Hello all,

I need to call a save function in my code behind when the user hits the Page Down key on the key board.  I already have the trapped key press event in javascript on my form.  I tried using a __dopostback and event argument but its throwing a script error everytime.  I don't want to worry about security settings on the user browser and I have to use the key press event unfortunately.  Any idea how I can do it?  The ascii key number is 34 so I have that ready to go I just need to know how to call my code behind method.
0
Comment
Question by:sbornstein2
11 Comments
 
LVL 30

Expert Comment

by:Reza Rad
ID: 26089938
why you want to use JavaScript?
is there any javascript function you want to use specially?

I asked this because i want to inform you that you can create an event handler for key press on your control like textbox, and then in this event call the method you want
0
 
LVL 3

Expert Comment

by:Saber37886661
ID: 26090753
you use onkeypress event on the textbox or form so it goes:
onkeypress="saveThis"

<script>
function saveThis(e)
{
    kc = e.keyCode?e.keyCode:e.which;
    if(kc==34)
    {
        alert("call the save function here");
    }
}
</script>
you may need a return false at the end of the javascript method to return a cancelled event. Im not 100% about that because I cant remember if you need it for all browsers or not.
0
 
LVL 9

Expert Comment

by:experts1
ID: 26090775
sbornstein2,

Please present a snippet of the current code you are working with, then we could get a better handle on how to help you modify code for desired results.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

Author Comment

by:sbornstein2
ID: 26091256
Saber how would I call an asp.net function from the javascript though thats my point.
0
 

Author Comment

by:sbornstein2
ID: 26091260
reza, they can hit the page down key anywhere not just on a control.
0
 

Author Comment

by:sbornstein2
ID: 26091277
attached is my exact code base and aspx page
ASPX PAGE WHERE THE USER CAN HIT ESC TO EXIT MODAL DIALOG OR PAGE DOWN TO SAVE THE CHANGES

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="mynotes.aspx.vb" Inherits="code.mynotes" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
	<head>
		<title>My Notes</title>
		<meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">
		<meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
		<meta name="vs_defaultClientScript" content="JavaScript">
		<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
		<link rel="stylesheet" type="text/css" href="StyleSheet1.css">
		<script language = "javascript">
		function set_focus()
		{
			document.getElementById("txtmemonew").focus();
		}

		function SetEnd(TB) {
		    if (TB.createTextRange) {
		        var FieldRange = TB.createTextRange();
		        FieldRange.moveStart('character', TB.value.length);
		        FieldRange.collapse();
		        FieldRange.select();
		    }
		}
		
		netscape = "";
		ver = navigator.appVersion; len = ver.length;
		for(iln = 0; iln < len; iln++) if (ver.charAt(iln) == "(") break;
		netscape = (ver.charAt(iln+1).toUpperCase() != "C");
		
		function keyDown(DnEvents,role) 
		{	// handles keypress
			// determines whether Netscape or Internet Explorer
			k = (netscape) ? DnEvents.which : window.event.keyCode;
			
			//esc
			if (k == 27) 
			{
				event.returnValue = false;
				window.close();
			}
			
			//page down
			if (k == 34) 
			{
//this is the page down ascii key and right now it goes to another window.  I also had this as an action in my form post before.  I don't however want to have to open up another page to handle the processing anymore.  I want to here call a code behind function in this form and then have the save code behind code and then the page refresh on the postback and show my changes.
			    
var avid = document.getElementById("avid").value;
			    window.open("notesprocess.aspx?avid=" + avid);
			    window.close();
			}
		}
		
		document.onkeydown = keyDown; // work together to analyze keystrokes
		if (netscape) document.captureEvents(Event.KEYDOWN|Event.KEYUP);
		</script>
	</head>
	<body onload="javascript: set_focus();">
	<form name=hotform>
	<table width=100% border=1 align=center cellpadding=0 cellspacing=0 bordercolor="9DB3C8" >
  <tr>
    <td height="20"> 
      <table border=0 align=center width=90% cellpadding=0 cellspacing=0>
					<tr>
						<td align=left class=sgparagraphs_medium_yellow>Esc - Exit</td>
						<td class=paragraphs_medium_yellow align=right>Page Dn  - Save Changes</td>
					</tr>
				</table>
		</table>
	</td>
</tr>
</table>

	<table width=100% align="center" bgcolor="9EB4CB">
	<tr>
            <td align=center> <textarea rows=8 cols=60 id=txtmemonew name=txtmemonew class=textarea_Flat_White onfocus="SetEnd(this)">
<%=strmemonew%>
</textarea></td>
</tr>
<tr>
            <td align=center> <textarea rows=15 cols=60 id=txtmemo name=txtmemo readonly="true" class=textarea_Flat_Gray>
<%=strmemo%>
</textarea></td>
</tr>
		</table>
		<input type = hidden name = page value = <%=m_page%>>
		<input type = hidden name = avid value = <%=Trim(request("avid"))%>>
</form>
</body>
</html>

CODE BEHIND:

Imports System.Data
Imports System.Data.SqlClient
Partial Class notes
    Inherits System.Web.UI.Page
#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region
    Public m_page, strsql As String
    Dim dr As SqlDataReader
    Dim objvalidate As New Validate()
    Public strmemo, strmemonew As String
    Public objcontact As New ContactClass()
    Public memocontents As String

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        Response.Buffer = True
        Response.Expires = 0
        Response.CacheControl = "no-cache"
        Session("hotpartflag") = "yes"

        strmemonew = Session("initials") & " " & FormatDateTime(Now(), vbShortDate) & " " & FormatDateTime(Now(), vbShortTime)

        m_page = Trim(Request("page"))
        strsql = "Select NOTES from NOTES where part_no='" & Trim(Request("avid")) & "'"
        dr = objvalidate.executereader(strsql)
        While dr.Read
            If Not IsDBNull(dr("Notes")) Then
                strmemo = (dr("Notes"))
            End If
        End While
        dr.Close()
        strmemo = strmemo
    End Sub

    Private Sub SaveNoteChanges()
        'this would be my save call
        memocontents = Request("txtmemonew")
        objcontact.UpdateNote(Trim(Request("avid")), memocontents)
    End Sub
End Class

Open in new window

0
 
LVL 3

Expert Comment

by:Saber37886661
ID: 26091382
ahh im with you :)

just put a button on the form, give it an event handler hide it and then call in by using document.getElementById("button blah").click()
0
 

Author Comment

by:sbornstein2
ID: 26091395
Saber I can't do that, I just posted another post as well about what I could try and do with the showmodaldialog box.  Long story but I cant use buttons etc. I can only have the key press event from what you can see in my javascript it will fire the ASCII code for the page down anytime the user clicks the key.  I cant have it tied to a certain control.
0
 

Author Comment

by:sbornstein2
ID: 26091424
This is what happens:

There is a main form which in that code behind based on an event a window.showopendialog gets called and this code you are seeing here attached is in that modal dialog.  The user types in some notes on this modal dialog and hits page down to save the changes.  I either wanted to be able to call on this modal dialog form the save directly in this form or what it used to have coded was a form submit and the action called a processing form.  In that processing aspx page the page load runs the save.   Then somehow I want to refresh the modal dialog and close the processing page down immediately because I dont want anything showing with the processing side as much as possible
0
 
LVL 3

Accepted Solution

by:
Saber37886661 earned 2000 total points
ID: 26093189
OK, I'm with you, finally!
insert this into the javascript
//this is the page down ascii key and right now it goes to another window.  I also had this as an action in my form post before.  I don't however want to have to open up another page to handle the processing anymore.  I want to here call a code behind function in this form and then have the save code behind code and then the page refresh on the postback and show my changes.
chr="?";
if(window.location.href.indexOf("?")!=-1){chr="&"; }
window.location.href+=chr+"save=true&avid="+document.getElementById("avid").value;

//Below is your old calls, I just left it in so you can get your bearings. You can remove it.
//window.location.href=+"?save=true&avid="+document.getElementById("avid").value;
//var avid = document.getElementById("avid").value;
//window.open("notesprocess.aspx?avid=" + avid);
//window.close();

The vb side just put this below the page_load event

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
If IsPostBack And Request("save") = "yes" Then
            SaveNoteChanges()
            Response.Write("<script>window.close();</script>")
End If

For me this does a postback on the page down button. The rest should be easy. Hopefully I have got it right this time!
0
 

Author Closing Comment

by:sbornstein2
ID: 31668215
thanks for all your help.  It is right I think but wont work for me because I am using a showmodaldialog to keep the popup on top so I need to figure out another way its driving me nuts.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The task A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome. So let’s take a number like this “12345678.91¿ and format i…
This article discusses how to implement server side field validation and display customized error messages to the client.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses
Course of the Month15 days, 19 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question