ASP.NET - How do I register multiple JavaScript calls to run on PostBack?

1.8k views Asked by At

I have an ASP.NET page with two instances of the same Web User Control (a simple WYSIWYG editor). On submit, the WUCs do a little JavaScript magic and then proceed with a normal postback.

The first instance seems to be working, but the second fails to post changes back to the server (it reverts to the original, and posts that). I believe the problem is that the JS only fires for the first WUC. I've traced that to the following code, from the generated client-side source:

function WebForm_OnSubmit() {
    prepHtml('AddEditPopup1_ctlEditorQuestion_txtEdit','AddEditPopup1_ctlEditorQuestion_divEdit', 'AddEditPopup1_ctlEditorQuestion_divHT' );        
    //snip...
}

The problem seems to be that there should be two calls to prepHtml: one for the ctlEditorQuestion instance of the WUC, and one for the ctlEditorAnswer instance.

Instead, there's only the one for ctlEditorQuestion. Both controls are registering the OnSubmit event, but one of them overwrites the other.

The prepHtml call is registered from the WUCs' C# code at runtime:

//Page_Load
_onSubmit = String.Format("prepHtml('{0}','{1}', '{2}' );", 
                txtEdit.ClientID, divEdit.ClientID, divHT.ClientID);

//OnPreRender
Page.ClientScript.RegisterOnSubmitStatement(this.GetType(), "get-html", _onSubmit);

I should point out that I didn't write this control myself, and I've never seen this kind of runtime registration of OnSubmit JS code before. Page.ClientScript.RegisterOnSubmitStatement is totally new to me.

I need to register both prepHtml calls so they run sequentially. Is this possible? I'm open to alternatives to Page.ClientScript.RegisterOnSubmitStatement, so long as the code still gets fired on submit.

1

There are 1 answers

8
Chris Gessler On BEST ANSWER

This should do what you want without tightly coupling the controls to the page.

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        string onSubmit = string.Format("prepHtml('{0}','{1}', '{2}';",
            txtEdit.ClientID,
            divEdit.ClientID,
            divHT.ClientID);

        Page.ClientScript.RegisterOnSubmitStatement(this.GetType(), 
            this.Id + "_getHtml", onSubmit);
    }
}

The key (as I mentioned in my comment) is the unique name. Notice that I use "this.ID" in the script name. The ID property is guaranteed to be unique within the page, so it would be a good candidate.