To send a value from javascript to the server you have a couple of options:
- Use AJAX if you want to stay on the current page
- Redirect to a server side script and pass the value in the querystring
Let's consider the first case:
Assuming you have a web method capable of receiving the value on the server:
<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" %>
<script type="text/C#" runat="server">
// Server side script in the code behind that will receive
// the value: The method needs to be static
// and decorated with the WebMethod attribute
[System.Web.Services.WebMethod]
public static string Foo(string id)
{
return "ok";
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head id="Head1" runat="server">
<title></title>
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
// Send an AJAX request to the server
$.ajax({
url: '/default.aspx/foo',
type: 'POST',
contentType: 'application/json; charset=utf-8',
// Pass the value as JSON string
// You might need to include json2.js for the JSON.stringify
// method: http://www.json.org/json2.js
data: JSON.stringify({ id: 'someId123' }),
success: function (result) {
// The result is also JSON
alert(result.d);
}
});
});
</script>
</head>
<body>
<form id="Form1" runat="server">
</form>
</body>
</html>