how do I handle KeyPress or KeyDown events in asp.net? - c#

KeyPress or KeyDown events aren't available in System.Web.UI.WebControls.TextBox so one way to do it is using Java-Scripts, but want to fire some Sql queries at these events. is it possible to execute Sql queries from JavaScript? if not then how do I do it?

No, You cannot execute SQL from javascript. Your best bet is to use something like jquery and wire up an event to .change() (or something simiiar) and then make an ajax request to perform the sql query. A server side event (which doesn't exist) for textbox key press or key down would submit the page everytime and that just wouldn't work for the user. You might look into jquery ui autocomplete if you're looking to display some information

If you need to capture key events, you'll need to use Javascript.
You can use ajax to then send these keys to the server and perform actions.
My guess is that you're thinking of something along the lines of Google Suggest.

You can handle the key press event in the given way
But you can't fire SQL queries in these events.
<%# Page Language="C#" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Label1.Text = "Start";
}
TextBox1.Attributes.Add("onkeyup", "rewriteLabel()");
}
</script>
<script type="text/javascript">
function rewriteLabel()
{
TextBox1.Text = Label1.text;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head >
<title >test</title>
</head>
<body>
<form id="form1" runat="server">
<br />
<asp:TextBox ID="TextBox1" runat="server" /><br />
<asp:Label ID="Label1" Runat="server" BorderWidth="1px" />
</form>
</body>
</html>

Related

How to change the form action in C# .NET through code?

I am working on a project in C# .NET that allows me only one form in the .aspx file.
<form id="form1" runat="server" action="#1">
How can I change the form action through the C# code in a method?
I have tried this:
protected void Button1_Click(object sender, EventArgs e)
{
form1.Action = "#2";
}
but it didn't work. Thanks in advance...
Based on the comments to you question. asp:Panel Controls could help you out.
A very rough example
ASPX:
<form id="form1" runat="server">
<asp:Panel id="Form1" runat="server">
<!-- Form 1 Stuff -- >
<asp:Button ID="Button1" runat="server" Text="Submit"
OnClick="Button1_Click" />
</panel>
<asp:Panel id="Form2" runat="server" Visible="false">
<!-- Form 2 Stuff -- >
<asp:Button ID="Button2" runat="server" Text="Submit"
OnClick="Button2_Click" />
</panel>
</form>
C#
protected void Button1_Click(object sender, EventArgs e)
{
//HIde "Form"1
Form1.Visible = false;
//Show "Form"2
Form2.Visible = true;
//Do other stuff
}
protected void Button2_Click(object sender, EventArgs e)
{
//Do Final Processig
}
Also look at the DefaultButton property of the Panel
(Moving this to the top because it's an answer to the newly understood question. It's not how to change the form action, but how to have multiple forms.)
If you want a server form on a page that already has a server form then perhaps that second "form" should be a User Control. That way it sits inside the host page's server form but doesn't require its own form. And it's self-contained, able to contain whatever logic it needs when handling a postback.
Here's an example of a simple User Control. You can create one from Add > New Item > Web > Web Forms User Control.
<%# Control Language="C#" AutoEventWireup="true"
CodeBehind="OtherForm.ascx.cs" Inherits="WebApplication1.OtherForm" %>
<label for="<% = OtherFormTextInput.ClientID %>">
This is some other form on the same page
</label>
<asp:TextBox runat="server" ID="OtherFormTextInput"></asp:TextBox>
<asp:Button runat="server" ID="Submit" Text="Submit this other form"/>
It looks like an .aspx page but it has no form. It can still have its own code behind which can interact with with the other server controls it contains, just like an .aspx page would.
Then you add that control to your "main" page:
<%# Page Language="C#" AutoEventWireup="true"
CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!-- Register the user control -->
<%# Register TagPrefix="uc" TagName="other" Src="~/OtherForm.ascx" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<!-- This form has its own stuff, but also contains the "other" form. -->
<uc:other runat="server" ID="TheOtherForm"></uc:other>
</form>
</body>
</html>
I recommend this over using panels (which still works) because if you're putting two forms on one page, it's likely that you might at some point want to move the secondary form to another page or re-use it. This approach keeps it completely self-contained. Its code-behind isn't in the same file as the the .aspx page. You can place this on as many pages as you want.
Original "literal" answer which addresses the question as originally understood.
The runat="server" form exists entirely for the purpose of allowing ASP.NET to interact with the page and its server controls during postbacks. It's central to the way webforms works. If you change the action then technically what you have isn't a webforms page any more.
That's fine (I don't even like webforms) but it can lead to some weird behavior. If you have controls that trigger postbacks then normally they'd be handled on the same page and your user would just see a (hopefully) fast refresh. Now they might get sent to another page.
What if you just removed that form entirely and added your own form instead? Then your .aspx page will just behave more like an .html page.
Having added all the disclaimers about why not to do it, you can change the action using JavaScript. Here's a sample:
<%# Page Language="C#" AutoEventWireup="true"
CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server" ClientIDMode="Static">
<asp:Button runat="server" text="Causes postback"/>
<asp:CheckBox runat="server" AutoPostBack="True"/>
</form>
<script>
document.getElementById("form1").action = "http://stackoverflow.com";
</script>
</body>
</html>
Some browsers might not allow changing the form's action.
I put the checkbox there just for fun (I must be really bored) to show the odd side effects it could have, that you might click on a checkbox and get redirected to a different page.
You can write a response.write() in your Asp.net side that print some javascript or jQuery code! As #Scott Hannen wrote some javascript like this :
Response.Write("<script>document.getElementById('YOURFORMID').action = 'YOUR URL';</script>");
or with jQuery
Response.Write("<script>$('#YOUR FORM ID').attr('action', 'YOUR URL');</script>");
btw if you have access to .html or .js files u can directly put this jQuery code without any C# code!

Creating form tag programmatically not working

I have a simple web page that contains a Literal, now I want to create a form tag in code behind.
This is an example:
if (IsPostBack)
{
Literal1.Text = "form submit";
}
else
{
Literal1.Text = "<form id='myFrom' runat='server' action='default.aspx'
method='POST'><input type='submit' value='click here'/></form>";
}
This code create the form, but when I click the submit button, it doesn't go through IsPostBack path. Why?
Note that I need it to be created and sent as an string, because I want to use it in ajax for example.
IsPostBack is only enabled when the POST request originates from ASP.NET's __doPostBack() function. See How to use __doPostBack() for how to create an async postback request with JavaScript.
An ASP.NET web form is already an HTML form and encompasses all of your controls. You are nesting a form within a form which is not legal HTML.
I'd suggest you replace your nested form with a simple button. In the click handler for the button, redirect to default.aspx.
As indicated by John Wu, you don't want to implement your code this way. Nested forms -- while browsers forgive them -- are just not the way to go, especially with ASP.Net WebForms. Sure, I was able to get your code to work, BUT if you need to ajaxify your page so that it works with the WebForms postback model, then it would be much better to use the UpdatePanel control (in conjunction with the ScriptManager control).
ASP.Net WebForms is predicated on only having a single Form element used on a page, as it relates to its postback model, so you'll want to work within that constraint.
Here's some code to demonstrate the use of the UpdatePanel to ajaxify a WebForm (and take advantage of PostBack):
...the .ASPX page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="NestedForm_Question.aspx.cs" Inherits="StackOverflowAspNetQuestionAnswers.NestedForm_Question" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager" runat="server" />
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Literal ID="Literal1" runat="server" />
<asp:Button ID="SubmitButton" Text="Submit" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
...the associated code-behind class:
public partial class NestedForm_Question : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SubmitButton.Click += SubmitButton_Click;
}
void SubmitButton_Click(object sender, EventArgs e)
{
Literal1.Text = "form submit";
}
}
You can see that in the code-behind class, the code that would need to be written to set the value of the literal control after the Button is clicked is the same whether the page is ajaxified or not.
I've changed my code to this:
if (Context.Request.Form.HasKeys()) // instead of if(IsPostBack)
{
Literal1.Text = "isPostBack";
}
else
{
Literal1.Text = "<form id='myFrom' runat='server' action='default.aspx' method='POST'><input type='submit' name='submitbtn' value='click here'/></form>";
}
Using different examples, I didn't find any exception to this. and it works well.
Any idea about this solution?
Note that in this way at least one of our elements in the form should have the name property.

Is Dirty in ASP.NET Web Page [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Detecting Unsaved Changes using JavaScript
My Web application has 3 web forms ,I implemented the validations in my webpage.I want to implement isdirty functionality in my web application.I want to pop up a message box in my webpage when a user clicks on sign out(which is a loginstatus control) if there any changes made to the form.
Environment:
Asp.net
VS2008
c#
This could be easily done with jquery and the onbeforeunload event. Using the .serialize() function you could calculate the state of the form on the returned string once when the page loads and then in the onbeforeunload event. Then compare the two values and if they are different something indeed has changed in the form.
Example:
<%# Page Language="C#" %>
<!DOCTYPE html>
<html>
<head id="Head1" runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
<script type="text/javascript">
var data = '';
$(function () {
data = $('form').serialize();
});
window.onbeforeunload = function () {
if ($('form').serialize() !== data) {
return 'You have unsaved changes. Are you sure you want to navigate away?';
}
};
</script>
</head>
<body>
<form id="Form1" runat="server">
<asp:TextBox ID="FirstName" runat="server" />
<asp:TextBox ID="LastName" runat="server" TextMode="MultiLine" />
<asp:CheckBox ID="Chk" runat="server" />
<asp:HyperLink ID="Link" runat="server" Text="Go to Google" NavigateUrl="http://www.google.com" />
</form>
</body>
</html>
Some other techniques (like the one presented in the duplicate question that was voted to close for your question) involve in subscribing for the .change() event of the input elements but they are less reliable as the user could for example type abc in some input field and then delete it and if you used this technique the form would be considered as dirty although no value actually changed.
You can easily setup a popup/modal window to show-up when the user tries to leave a form/page. Here is a quick pure javascript example, that shows a message when you try to leave a page.
<body onunload="if (confirm('Save form ?')) { SaveFormMethod(); }">
If you need a better example, you should provide more details and show us your code.
Please take a look at this answer and see if it helps

Run a Javascript function before postback

On my ASPX page, there is a button with this code:
OnClick="save_Click"
Is it possible to execute Javascript before postback and if the result is true, then do the postback and go to method save_click?
There is a property called "OnClientClick" as well. Here you can specify a function that will validate (I'm guessing), or just run regular javascript.
If your data is not valid you can just return false; from the method. That should cancel your postback
you should use the very well known way: return confirm('bla bla bla')
adding this snippet to the onclick attribute of the button in the page or button prerender method, server side...
http://msdn.microsoft.com/en-us/library/7ytf5t7k.aspx
<%# Page Language="C#" %>
<script runat="server">
protected void Button1_Click(Object sender, EventArgs e)
{
Label1.Text = "Server click handler called.";
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<body>
<form id="form1" runat="server">
<asp:Button ID="Button1" Runat="server"
OnClick="Button1_Click"
OnClientClick="return confirm('Ready to submit.');"
Text="Test Client Click" />
<br />
<asp:Label ID="Label1" Runat="server" text="" />
</form>
</body>
</html>
Possible duplicate of : Execute ClientSide before ServerSide in ASP.NET
I changed the definition of the __doPostback function to accomplish this:
<script type="text/javascript">
var originalDoPostback = __doPostBack;
__doPostBack = function (p1, p2) {
doSomethingCustomHere();
originalDoPostback(p1, p2);
};
</script>

Execute ClientSide before ServerSide in ASP.NET

I am using ASP.NET 3.5.
When the user click on say btnSubmit I want to first execute some JavaScript code and then execute some C#/VB.NET code.
Is this possible? If so how would one do it?
Thanks in advance!
This is very simple:
http://msdn.microsoft.com/en-us/library/7ytf5t7k.aspx
<%# Page Language="C#" %>
<script runat="server">
protected void Button1_Click(Object sender, EventArgs e)
{
Label1.Text = "Server click handler called.";
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<body>
<form id="form1" runat="server">
<asp:Button ID="Button1" Runat="server"
OnClick="Button1_Click"
OnClientClick="return confirm('Ready to submit.');"
Text="Test Client Click" />
<br />
<asp:Label ID="Label1" Runat="server" text="" />
</form>
</body>
</html>
Have the JavaScript execute and then call a web service with xmlhttprequest from the javascript
There is onClientClick property - check this out http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick.aspx
Of course, you simply add an onClick event all JS code is executed before the postback.
If the code is for validation and you decide you don't want to submit you can return false and it won't post.
<asp:Button OnClientClick="" />
Thanks for the answer guys!
To execute a function from code behind one would do this in VB.NET
Protected Sub btnSubmit_Click(blah blah) Handles btnSubmit.Click
ClientScript.RegisterStartupScript(Me.GetType(), "hiya", "Message()", True)
lblLabel.Text = "Hello my name is Etienne!"
End Sub

Categories