开发者

Setting js to execute from server in ASP.NET Application

开发者 https://www.devze.com 2023-03-01 03:36 出处:网络
I\'m working on a asp.net application. There is a lot of UpdatePanels used. Is there any \"best practice\" way to set some js scripts for execute after updatePanel is refreshed. (It is important : js

I'm working on a asp.net application. There is a lot of UpdatePanels used. Is there any "best practice" way to set some js scripts for execute after updatePanel is refreshed. (It is important : js scripts are not static - for example I'm handling exception in my server-side code and I need to get user aware of this exception after 开发者_StackOverflowupdatePanel is refreshed e.g.)

Currently I'm using the following solution:

<asp:Hidden id="scriptsHiddenField" runat="server" />

In server side i'm passing scripts like that:

catch (Exception exception) {
   scriptsHiddenField.Value += String.Format("alert('Oops! Error occured: {0}');", exception.Message);
}

And I'm evaluating scripts on endRequest event in the following way:

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);

function endRequestHandler(sender, args) {
    eval($('#<%= scriptsHiddenField.ClientID %>').val());
    $('#<%= scriptsHiddenField.ClientID %>').val('');
}

That is just an sipmlified example, so basically it is not only error handling which has to work like that. Normally the scripts passed from the server are more complex, so I've got bad feeling about evaluation js in that way.


We do something similar all the time. Here's a function which calls a javascript alert when the update panel refreshes.

public static void ShowInUpdatePanel(string message, UpdatePanel up)
{
    //Cleans the message to allow single quotation marks
    string cleanMessage = message.Replace("'", "\\'");
    string script = "<script type='text/javascript'>alert('" + cleanMessage + "');</script>";
    ScriptManager.RegisterStartupScript(up, up.GetType(), "alert" + DateTime.Now.Millisecond.ToString(), script, false);

}


ScriptManager.RegisterStartupScript(this, GetType(), "somenameyouwanttouse", "alert('xyz');", true);

Edit: the last parameter defines if you want to emit the SCRIPT tag automatically. Forgot in my initial answer.

Also, ClientScript.RegisterStartupScript is similar, but will not run after each async postback (only the first one), if I am not mistaken.


have you tried registering a startup script to be run after the update?

catch (Exception exception)
{
      ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "errkey", "alert('Oops! Error occured: " + exception.Message + "');", true);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消