首页 > 解决方案 > 如何显示等待用户输入的对话框?

问题描述

我习惯了 Windows 窗体,但标准MessageBox.Show()在 ASP.NET 项目中不可用。这可以在 ASP.NET WebForm 项目中完成吗?

假设我有几个例程:

DatabaseRoutine();
GotoAnotherPageRoutine();

DatabaseRoutine()调用数据库并具有 TRY/CATCH 块:

public void DatabaseRoutine()
{
    try {
        // code here that may fail
    } catch (Exception error)
    {
        var scriptManager = Page.ClientScript;
        var cstype = this.GetType();
        var csname1 = "DatabaseRoutine";
        if (!scriptManager.IsStartupScriptRegistered(cstype, csname1)) {
            var script = String.Format("<script runat=\"server\">alert('{0}: {1}');</script>", csname1, message);
            scriptManager.RegisterStartupScript(cstype, csname1, script, true);
        }
    }
}

上面的catch例程将被提取到一个错误处理方法中,该方法可以由可能有错误的代码的其他部分调用。

当前的问题是在ScriptManagerGotoAnotherPageRoutine()调用 Javascript Alert之后将立即调用下一个例程,因此它永远不会显示给最终用户。

我们还有什么可以向最终用户显示消息?

出于几个原因,不建议将重定向 URL 添加到警报框(重定向并不总是相同,并且重定向通常嵌套在基于数据库条目的其他决策制定任务中)。

标签: javascriptc#htmlasp.net

解决方案


也许你可以试试这样的东西

try {
  DatabaseRoutine();
  GotoAnotherPageRoutine();
} catch (Exception ex) { ShowModalError() ... }

public void DatabaseRoutine()
{
.. do some stuff without any try catch
}

或者

try {
      DatabaseRoutine();
      GotoAnotherPageRoutine();
    } catch (Exception ex) { ShowModalError() ... }

    public void DatabaseRoutine()
    {
       try {
          .. do some stuff 
       }
       catch (Execpetion ex)
      {
       ..log exception on db .. 
        throw ex // rethrow exception
      }
    }

要获得更好的弹出窗口,您可以使用 ajaxcontroltoolkit 和 modalpopupextender 控件


推荐阅读