My page has a submit button on it (server-side button).
Here's my code for the click event:
protected void SubmitButton_Click(object sender, EventArgs e)
{
db.SaveSomething();
Page.ClientScript.RegisterStartupScript("someScriptWhichReliesOnServerData");
Response.Redirect("SomeOtherPage.aspx");
}
Now, the problem is, i register the JavaScript using Page.ClientScript.RegisterStartupScript
, but this will have no effect as the page is not being re-rendered on postback (which is where the script WOULD be executed), because instead a Response.Redirect
happens.
The only solution i can think is to make the page i redirect to "aware" that im trying to execute some JavaScript, be it QueryString, HttpContext.Current.Items, or (gulp) Session.
- QueryString - not an option, as it's JavaScript im trying to execute.
- HttpContext.Current.Items - also not an option because im doing a Response.Redirect (which loses the request-level data, and i also cannot use Server.Transfer because this doesn't play nice with URL Rewriting).
- Session - of course, but not ideal.
Any other ideas/suggestions?
EDIT for Clarification:
The JavaScript im executing is a call to a Facebook client-side API to publish to the user's wall. It has to be done client-side. I pass to the script things like "title", "message", "action links", etc. Basically a bunch of JSON. But the key here is that this data is created on postback, so i cant just execute this function on client-side click.
So what im trying to accomplish is on submit button click, execute some javascript and do a redirect (does not have to be in that order, just both need to happen).
I think what you are experiencing is the unfortunate clashing of two different paradigms here. On the one side you have an AJAX style API you want to take advantage of, and on the other side you have the ASP.Net page postback model.
Now, while these two are not mutually exclusive, it can present some challenges. I agree with Dan that your best bet is to bend a little more towards the AJAX approach instead of the other way around.
A nice feature in ASP.Net is the ability to turn a single static method in your page into a pseudo web service. You can then use the ScriptManager to generate client-side proxy classes to call that method for you, but you can use whatever client side library you want.
A very simple example:
In your codebehind for you Page
If you were using the ASP.Net AJAX library to handle this for you, then you would need to enable page methods to generate the client-side proxies.
Then you could call that from client-side script like so:
Now again, this is a contrived example, and what you are posting to the server may be very complicated, but you get the general idea of what can be accomplished using the built in framework components.
I hope this helps.