0

Riddle me this, SO. I have two buttons:

<div class="btn-group" role="group">
    <asp:Button runat="server" ID="RegisterButton" ClientIDMode="Static" OnClick="RegisterButton_Click" Text="register" />
    <asp:Button runat="server" ID="TestButton" ClientIDMode="Static" OnClick="TestButton_Click" Text="testClick" />
</div>

Which call two different functions:

protected void RegisterButton_Click(object sender, EventArgs e)
{
...
Register(user)
}
private void Register (user)
{
...
RegisterResultResultJson(regRes);
}
private void RegisterResultResultJson(RegResult regResult)
{
    string jsonString = Helpers.Serializer.JsonSerializer.ToJSON(regResult);
    string script = ";RegisterResult(" + jsonString + ");";
    ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "RegisterStartupScript", script, true);
}
protected void TestButton_Click(object sender, EventArgs e)
{
    string script = ";console.log('klik');";
    ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "RegisterStartupScript", script, true);
}

When I click TestButton, everything works as expected, I can see script in source and console logs "klik". But when I click RegisterButton nothing happens. When I put breakpoint into code, copy script and paste it into console, JS RegisterResult() works properly.

Kajbo
  • 1,068
  • 3
  • 16
  • 31

1 Answers1

1

But when I click RegisterButton nothing happens

What's happening is that when you execute this code:

string script = ";RegisterResult(" + jsonString + ");";
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "RegisterStartupScript", script, true);

This is just pasting a script code in the web page and not invoking the function

<script type="text/javascript">
  //<![CDATA[
 ;RegisterResult(yourDatacomesHere);//]]>
</script>

So if you want to invoke the function, instead of pasting that in the script tag simply call the function as:

ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "registerButtonClick", "RegisterResult("+jsonString+")", true);

Or you can bind your code in an IIFE.

string script = "(function(){RegisterResult(" + jsonString + ");})()";
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "registerButtonClick", script, true);

Note: for future reference if possible try to use the WebMethods which can be called from the client side (using ajax or simple javascript) which can return you the value back in the client side in the success or failure function.

vikscool
  • 1,293
  • 1
  • 10
  • 24