Often we need to bring some client side data (e.g. javascript variable’s value) into the server side for processing. Doing this usually done using hidden fields- registering hidden fields from server and modifying the values at client side using javascript and finally bringing back the modified value to the server along with a post back. I was going to do this same task from within an ASP.NET Ajax application. And I found that if using a handler for client side add_beginRequest is not sufficient to accomplish this task. The reason is the begin request is fired by the ASP.net AJAX after preparing the request object. So changing the value inside this method will not reflect the value at server side.
Here is the way how we can resolve this problem. First of all we are going to register a hidden field from the server side
protected
void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack){
ScriptManager.RegisterHiddenField(UpdatePanel1, “HiddenField1”, “”);
}
}
Now at the client side, we need to register a handler for the begin_request event of ASP.NET AJAX client side script manager.
<script
type=”text/javascript”>
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(onBeginRequest);
Now, we need to modify the request object (inserting the data that we need to bring at the server end) just before it gets posted into the server. Here is how we can do it.
function onBeginRequest(sender, args)
{
var request = args.get_request();
var body = request.get_body();
var token = ‘&HiddenField1=’;
body = body.replace(token, token + document.getElementById(‘someElementID’).value);
request.set_body(body);
}
Here we are opening the request object and modifying the request body by inserting the value found at a text input element.
Now at server end you will find this value
protected
void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) {
ScriptManager.RegisterHiddenField(UpdatePanel1, “HiddenField1”, “”);
}
else {
string etst = Request[“HiddenField1”]; // reading the value here!
}
That’s it!