So, i have an aspx page which looks like this:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
I would like to know, how I can write JavaScript (e.g. jQuery) code that will call a function from my C# Code. Lets say this is my C# method:
protected void XXX(object sender, EventArgs e)
{
Response.Redirect("pagewho?");
}
Thanks again, Alon. 🙂
EDIT:
This is the full code i am using the moment:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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></title>
</head>
<body>
<script type="text/javascript">
validateStuff = function () {
var isValid = true;
var txt = document.getElementById("TextBox1");
if (txt) {
if (txt.value.toLower() != "james") {
isValid = false;
}
}
//perform validation and return true/false
return isValid;
}
</script>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" OnClientClick="return validateStuff();" OnClick="Button1_Click" />
<br />
<br />
<asp:TextBox ID="TextBox1" runat="server" Height="25px" Width="135px"></asp:TextBox>
<br />
<br />
<br />
</div>
</form>
</body>
</html>
but, no matter what i am wireting in the textbox, its return true. any help?
You can use
__doPostBackfrom the script, and use the RaisePostBackEvent method in the code behind to perform your server-side logic. If you’re looking to do a redirect, this would probably be the best way.EDIT
If you’re looking to do some validation in JavaScript when a button is clicked, use
OnClientClickto perform your JavaScript validation, and return true if the validation succeeds.Your JavaScript validation:
If the
validateStufffunction returns true, a postback will occur and you can handle your save/update logic in the button click event:In JavaScript:
In the code-behind:
If all you’re looking to do is bring the user to another page, you can also do this: