简体   繁体   中英

Calling a Javascript function from .cs

I have an Update panel where a button and a grid are added as follows: this._UpdatePanel.ContentTemplateContainer.Controls.Add(this._BtnSave); this._UpdatePanel.ContentTemplateContainer.Controls.Add(this._AssignGrid);

On click of this button I am calling a function which resides in a different class AssignedGrid.cs. this._AssignedGrid.getSelectedRows();

AssignedGrid.cs inturn calls a javascript function as follows:

  public void getSelectedRows()
  {
      this.Page.ClientScript.RegisterStartupScript(Page.GetType(), "GetSelectedItems", "<script type='text/javascript' language='javascript'>GetSelectedItems();</script>");    
  }

But this javascript function is never called! Please let me know if I am calling the function the proper way.

你不必给脚本标签

ScriptManager.RegisterStartupScript(this, GetType(), "GetSelectedItems", "GetSelectedItems();", true);

This should work,

ScriptManager.RegisterStartupScrip(this.Page, this.Page.GetType(), "GetSelectedItems", "GetSelectedItems();", true);

The first parameter of the Script manager expects a page object ( http://msdn.microsoft.com/en-us/library/bb310408(v=vs.110).aspx )

This is probably a user control, web control, etc and not an actual page object, as such it doesn't work. The only time this works is if you are in the context of a page, eg like a class that inherits from page.

So just send it the page object explicitly.

Once you have that, if it's not getting called, use a browser like Chrome, open the developer tools (f12) and go to the console window and look for javascript errors. If it was called but wasn't found you should see "GetSelectedItems does not exist" or a similar error. And that would mean your function is being declared and loaded after the code that calls it was inserted in the dom order by the ScriptManager.

The ScriptManager will insert the code call at the end of the page before the close tag, so define GetSelectedItems in the tag or somewhere above it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM