views:

88

answers:

3

How to call a javascript function inside server side after the code is executed in page load/any events ? I am using UpdatePanel in this page. I had tried Page.RegisterStartUpScript, ClientScript.RegisterStartupScript. None of this works.

+2  A: 

With an UpdatePanel you need to use ScriptManager.RegisterStartupScript, like this:

var script = "alert('hi);";
ScriptManager.RegisterStartupScript(this, GetType(), "MyScript", script, true);

You have to remember in an UpdatePanel, you're not sending the whole page back to the client, so the Page versions won't work, because their content never goes anywhere on a partial update. With ScriptManager it actively shoves this into the AJAX response it's sending as a script to execute, so it's behaving a little differently.

Nick Craver
I have tried this. It works. But I am unable to call a Script Function. I need to call a script function ie a custom built function or script block
Sreejesh Kumar
@Sreejesh - You can call `myFunction("something")`, etc...anything you want, think of this as being `<script type="text/javascript">myFunction("something");</script>` on the client side....is that not what you're after?
Nick Craver
yes. I haven the code in server side as string script = "DisplayM();";ScriptManager.RegisterStartupScript(this, GetType(), "MyScript", script, true);In the script function, I have written the script to show alert message. But its not working.
Sreejesh Kumar
@Sreejesh - Do you get a JavaScript error in the page? If `DisplayM` is defined, this should work. Check your console for errors to see what's erroring out, that's the area that needs fixing here if `alert()` works fine.
Nick Craver
Sorry...its working !!!!!!
Sreejesh Kumar
@Sreejesh - Excellent, yay for Friday victories :)
Nick Craver
Thanks. But now I got another problem. The actual function which I created was for calling jquery ajax, to perform a server side code during drag and drop an item process. After the item is dropped, now I am unable to drag the item. I think I need to reload the jquery drag and drop events. When I reloaded, A script is occurring
Sreejesh Kumar
@Sreejesh - If the drag items are in an update panel, you'll need to re-run `.draggable()` or whatever plugin you're using once it completes, either as part of your function or using `add_endRequest` to always run it, you can find more info on that here: http://stackoverflow.com/questions/256195/jquery-document-ready-and-updatepanels
Nick Craver
ok. Where should I put add_endRequest ?
Sreejesh Kumar
@Sreejesh - Follow the answers in that question, you just need to put it once in your page...the function you pass to it will execute every time an UpdatePanel finishes :)
Nick Craver
Hello Nick. I tried this. Still its not working. I think that function is not reloading. So when I click the node for dragging, a script error appears saying "htmlfile: Unspecified error."
Sreejesh Kumar
A: 

ScriptManager.RegisterStartupScript

Registers a startup script block for a control that is inside an UpdatePanel by using the ScriptManager control, and adds the script block to the page.

rick schott
+1  A: 

Hey there,

Just yesterday I did some research to help a fellow co-worker out and came up with the following solution. It relys on some techniques used in ajax control extenders in the use of registering data items. Since I wanted this to be more of a generic approach, I placed the following code in a script block in the master page just after the scriptmanager object:

Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(PageLoadingHandler); function PageLoadingHandler(sender, args) { var dataItems = args.get_dataItems(); if ($get('<%=JSBridge.ClientID%>') !== null) { eval(dataItems['<%=JSBridge.ClientID%>']); } }

Then somewhere in the markup of the master page I placed a hiddenfield as in:

asp:HiddenField ID="JSBridge" runat="server"

That's it for the master page. Now, all of my webpages inherit from a base page so I placed a method in the base page as in:

public void InvokeScriptMethod(string methodName, string[] methodArgs) { string sArgs = string.Empty; string delim = string.Empty; bool isNumeric = false; int iArg = 0;

        if (methodArgs != null && methodArgs.Length > 0)
        {
            foreach (string arg in methodArgs)
            {
                isNumeric = int.TryParse(arg, out iArg);
                sArgs += delim + ((isNumeric) ? arg : "'" + arg + "'");
                delim = ",";
            }
        }

        ScriptManager manager = (ScriptManager)Master.FindControl("ScriptManager1");

        if (manager.IsInAsyncPostBack)
        {
            manager.RegisterDataItem(Master.FindControl("JSBridge"), methodName + "(" + sArgs + ")");
        }
    }

So, assuming your content is inside an update panel, any button clicks or any event for that matter, on any web page, you can simply do the following:

protected void MyButton_Click(object sender, EventArgs e) { //-- Call base page method to invoke javascript call InvokeScriptMethod("ShowMessage", new string[] { "David", "Whitten", "44" }); }

This is assuming you have a javascript method out there somewhere called "ShowMessage" with the necessary parameters. Obviously, one can specify any method name and any numbers of parameters.

Just wanted to share my findings. Maybe there is even a better way but I find this pretty simple and flexible.

David

David