1

I am fairly new to js and am having trouble when trying to call a js function from my codebehind.

C#:

protected void GridView3_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            tbListOfCountries.Text = GridView3.SelectedRow.Cells[1].Text;
            Page.ClientScript.RegisterStartupScript(this.GetType(), "test", "test()", true);   
        }

JavaScript:

 function test() {
       alert("test");     
    }

And the Unexpected Identifier error:

//<![CDATA[
test()Sys.Application.add_init(function() {
    $create(Sys.Extended.UI.TabPanel, {"headerTab":$get("__tab_TabContainer1_TabPanel1"),"ownerID":"TabContainer1","wasLoadedOnce":true}, null, {"owner":"TabContainer1"}, $get("TabContainer1_TabPanel1"));
});

Any insights?

TestNInja
  • 167
  • 1
  • 15
  • 1
    Possible duplicate of [How to call javascript function from code-behind](https://stackoverflow.com/questions/4848678/how-to-call-javascript-function-from-code-behind) – PaulF Sep 14 '17 at 15:47

2 Answers2

3

It looks like your script test() isn't syntactically correct. Try replacing with test();

DiskJunky
  • 4,568
  • 3
  • 35
  • 65
1

If you're running this in an UpdatePanel you may encounter some issues (especially on PostBack). I find this version works best:

Control sender = MyUpdatePanel;
string javaScript = "alert('Hello');"; 
ScriptManager.RegisterStartupScript(sender, sender.GetType(), Guid.NewGuid().ToString(), javaScript, true);

You'll need a ScriptManager tag on the page:

<asp:ScriptManager ID="MyScriptManager" runat="server" />
Hugo Yates
  • 2,046
  • 2
  • 25
  • 24
  • I've tried your example and it works for the alert, however, when I try to set `string javascript` to the name of my function, it is no longer firing. Am i missing something? – TestNInja Sep 14 '17 at 16:29
  • Your function maybe out of context, is it at the top of the page or at the bottom? And is it nested in an UpdatePanel? Press F12 on your browser and see the Console for javascript errors this will give you a better indication of that's gone wrong. – Hugo Yates Sep 15 '17 at 08:36