Daniel
Daniel

Reputation: 1263

Pass data to server side from Javascript code

I'm trying to send data from client-side to server-side (asp.net c#), if you really want to know, I want to send the window.name property.

First I thought about having a asp:HiddenField and on the OnSubmit event have some JS write the value in the hidden field. The only problem is that I can access the hidden field value (according to this) only from PreLoad event to PreRenderComplete event. The project that I'm working on has a lot of code in the OnInit event, and unfortunately I cannot move it and I need to use the window.name value here.

The other ideas that I have is to add a custom HTTP Header windowId or on the OnSubmit event have a JS that appends a parameter to the document.location.href.

I managed to write to the header from JS with the XMLHttpRequest setRequestHeader, but, maybe I did something wrong in my implementation, this generates 2 requests, the first one is the normal, expected one(clicking a button/link ...) and the second is from the XMLHttpRequest. I find this behavior very unnatural. Do you have any sugestions? (see code snippet below). I do not what to use AJAX.

    var oReq = new window.XMLHttpRequest;
    oReq.open('POST', document.location, false);
    oReq.setRequestHeader("windowId", window.name);
    oReq.send(null);

For the OnSubmit hook idea, i haven't spent to much time on it, but i think I have to append the # character before i append my windowId parameter with it's value, so that the page doesn't reload. I might be wrong about this. Any way, I have to remove this from the URL after I take the value, so that the user doesn't see the nasty URL. Do you have any sugestions?

Ok so what are your ideas?

Thank you for reading all my blabbering, and thank you, in advance, for you answers.

Upvotes: 0

Views: 1489

Answers (1)

pete
pete

Reputation: 25081

I would recommend the <asp:HiddenField /> (e.g., <asp:HiddenField ID="hfWindowName" runat="server" />. In OnInit you can still access its value by using Request.Form:

string windowName = Request.Form(hfWindowName.UniqueID);

Upvotes: 1

Related Questions