如何调用window.alert("message"); 来自C#?

Nay*_*han 16 c# asp.net

基于某些条件我有自己的异常,并且当控制进入此catch块时想要发出警报

catch (ApplicationException ex)
{
    //want to call window.alert function here
}
Run Code Online (Sandbox Code Playgroud)

Rue*_*uel 28

你的意思是,一个消息框?

MessageBox.Show("Error Message", "Error Title", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
Run Code Online (Sandbox Code Playgroud)

更多信息请访问:http://msdn.microsoft.com/en-us/library/system.windows.forms.messagebox(v = VS.100).aspx

  • 不。问题是关于网络应用程序,而不是桌面应用程序。 (2认同)
  • 在他第一个没有问题的问题上,标签上写着`c#`和`.net`. (2认同)

Jam*_*iec 11

在没有更多信息的情况下给出确定的答案有点困难,但通常的方法是注册启动脚本:

try
{
  ...
}
catch(ApplicationException ex){
  Page.ClientScript.RegisterStartupScript(this.GetType(),"ErrorAlert","alert('Some text here - maybe ex.Message');",true);
}
Run Code Online (Sandbox Code Playgroud)


Esl*_*awy 6

如果你在你的页面中使用ajax需要脚本管理器Page.ClientScript
将无法正常工作,试试这个它会做的工作:

ScriptManager.RegisterClientScriptBlock(this, GetType(),
            "alertMessage", @"alert('your Message ')", true);
Run Code Online (Sandbox Code Playgroud)


aba*_*hev 5

您可以从任何网页或嵌套用户控件使用下一个扩展方法:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

下一步:

class YourPage : Page
{
    private void YourMethod()
    {
        try
        {
            // do stuff
        }
        catch(Exception ex)
        {
            this.ShowAlert(ex.Message);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)