How to call window.alert(“message”); from C#?

后端 未结 10 2309
春和景丽
春和景丽 2021-02-07 05:18

I have my own exception based on some condition and want to raise an alert when control comes in this catch block

catch (ApplicationException ex)
{
    //want t         


        
相关标签:
10条回答
  • 2021-02-07 05:49

    It's a bit hard to give a definitive answer without a bit more information, but one usual way is to register a startup script:

    try
    {
      ...
    }
    catch(ApplicationException ex){
      Page.ClientScript.RegisterStartupScript(this.GetType(),"ErrorAlert","alert('Some text here - maybe ex.Message');",true);
    }
    
    0 讨论(0)
  • 2021-02-07 05:49

    if you are using ajax in your page that require script manager Page.ClientScript
    will not work, Try this and it would do the work:

    ScriptManager.RegisterClientScriptBlock(this, GetType(),
                "alertMessage", @"alert('your Message ')", true);
    
    0 讨论(0)
  • 2021-02-07 05:51

    You can use the following extension method from any web page or nested user control:

    static class Extensions
    {
        public static void ShowAlert(this Control control, string message)
        {
            if (!control.Page.ClientScript.IsClientScriptBlockRegistered("PopupScript"))
            {
                var script = String.Format("<script type='text/javascript' language='javascript'>alert('{0}')</script>", message);
                control.Page.ClientScript.RegisterClientScriptBlock(control.Page.GetType(), "PopupScript", script);
            }
        }
    }
    

    like this:

    class YourPage : Page
    {
        private void YourMethod()
        {
            try
            {
                // do stuff
            }
            catch(Exception ex)
            {
                this.ShowAlert(ex.Message);
            }
        }
    }
    
    0 讨论(0)
  • 2021-02-07 05:55

    MessageBox like others said, or RegisterClientScriptBlock if you want something more arbitrary, but your use case is extremely dubious. Merely displaying exceptions is not something you want to do in production code - you don't want to expose that detail publicly and you do want to record it with proper logging privately.

    0 讨论(0)
  • 2021-02-07 06:02

    I'm not sure if I understand but I'm guessing that you're trying to show a MessageBox from ASP.Net?

    If so, this code project article might be helpful: Simple MessageBox functionality in ASP.NET

    0 讨论(0)
  • 2021-02-07 06:03

    You can also do this :

     catch (Exception ex)
        {
    
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "showError",
               "alert('" + ex.Message + "');", true);
    
        }
    

    this will show the exeption message in the alert box

    0 讨论(0)
提交回复
热议问题