3

I am using RegisterClientScriptBlock to send a JS alert to the user when the users goes into edit mode on a gridview, but it causes my page to error for some reason and I can't figure out why...

This is the method that causes the problem. The error occurs in the last line where the script is registered. (If I comment this out the page works fine!)

    protected void EditRecord(object sender, GridViewEditEventArgs e)
    {

        gvStockItems.EditIndex = e.NewEditIndex;
        // Gather current Search info
        string strPartNo = Session["currentSearchTerm"].ToString();
        BindData();
        gvStockItems.SelectedIndex = gvStockItems.EditIndex;
        Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "thisIsTest", "<script language=\"text/javascript\">alert(\"oops\");</script>");
    }

The error that is thrown in the JS console is

Uncaught Sys.WebForms.PageRequestManagerServerErrorException: Sys.WebForms.PageRequestManagerServerErrorException: Object reference not set to an instance of an object.

It also says that this error occurred in Error$Create in the ScriptResource.axd, but I think this is an error that occurs on reporting what the real issue is, so I'm completely stumped.

Any help is greatly appreciated. Thanks.

Ben Drury
  • 1,356
  • 2
  • 16
  • 34

2 Answers2

4

remove Page.ClientScript.RegisterClientScriptBlock and try using RegisterStartupScript

// Define the name and type of the client scripts on the page.
String csname1 = "thisIsTest";
Type cstype = this.GetType();

// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;

// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
    StringBuilder cstext1 = new StringBuilder();
    cstext1.Append("<script type=text/javascript> alert('oops!') </");
    cstext1.Append("script>");

    cs.RegisterStartupScript(cstype, csname1, cstext1.ToString());
}

OR if you have ScriptManager then

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "thisIsTest", "alert('oops!');", true);  
Damith
  • 62,401
  • 13
  • 102
  • 153
1

It appears to be to do with call registering scripts from code behind when doing only partial update within an update panel. If I set EnablePartialRendering="false" in the script manager it all works fine. Where as if I allow partial rendering the error occurs.

Damith
  • 62,401
  • 13
  • 102
  • 153
Ben Drury
  • 1,356
  • 2
  • 16
  • 34
  • You can add the 4th parameter to RegisterStartupScript (make it True) and avoid adding messy ` – Yuriy Galanter Jun 19 '12 at 15:47