Asp.net MessageBox并不存在于上下文中

时间:2013-11-10 07:55:27

标签: c# asp.net

我在asp.net中创建了一个连接类,用于保存列表中的值,我编写了以下代码,但它产生的错误MessageBox不存在。我谷歌这个并找到了 答案很少,但这些也不起作用我的代码是:

 public static class Connection
    {
        public static ArrayList GetCoffeeByType(string coffeetype)
        {
            ArrayList list = new ArrayList();
            try
            {
                mydbEntities db = new mydbEntities();
                var query = from p in db.tableabc select p;
                list = query.ToList();

            }
            catch (Exception ex)
            {
               MessageBox.Show(exceptionObj.Message.ToString());

            }
            return list;
        }
}

我试过这个System.Web.UI.ScriptManager.RegisterStartupScript(this, typeof(Page), "alert", "alert('" + Message + "')", true); - 但它也在thisMessage显示错误 - 如何显示此MessageBox?

2 个答案:

答案 0 :(得分:3)

您将无法在ASP.NET应用程序中调用MessageBox.Show。试试这个:

catch (Exception ex)
{
    var script = "alert(" + System.Web.HttpUtility.JavaScriptStringEncode(ex.Message, true) + ")";
    System.Web.UI.ScriptManager.RegisterStartupScript(this, typeof(Page), "alert", script, true);
}

请注意,您需要在捕获的异常Message上获取ex属性,并且应使用JavaScriptStringEncode安全地转义警报消息。

答案 1 :(得分:1)

这是一个名为Alert的静态类,它有一个名为Show的公共方法。实现尽可能简单。只需将.cs文件放在您网站上的App_Code文件夹中,即可从所有页面和用户控件中访问该方法。

using System.Web;
using System.Text;
using System.Web.UI;

/// <summary>
/// A JavaScript alert
/// </summary>
publicstaticclass Alert
{

/// <summary>
/// Shows a client-side JavaScript alert in the browser.
/// </summary>
/// <param name="message">The message to appear in the alert.</param>
publicstaticvoid Show(string message)
{
   // Cleans the message to allow single quotation marks
   string cleanMessage = message.Replace("'", "\\'");
   string script ="<script type=\"text/javascript\">alert('"+ cleanMessage +"');</script>";

   // Gets the executing web page
   Page page = HttpContext.Current.CurrentHandler as Page;

   // Checks if the handler is a Page and that the script isn't allready on the Page
   if (page !=null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
   {
      page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script);
   }
}    
}

<强>示范

该类允许您随时向任何页面添加JavaScript警报。以下是使用该方法显示状态消息的Button.Click事件处理程序的示例。

void btnSave_Click(object sender, EventArgs e)
{
   try
   {

      Alert.Show("Your Message");
   }
   catch (Exeception ex )
   {
      Alert.Show(ex.Message);
   }
}

在你的案例中:

public static class Connection
    {
        public static ArrayList GetCoffeeByType(string coffeetype)
        {
            ArrayList list = new ArrayList();
            try
            {
                mydbEntities db = new mydbEntities();
                var query = from p in db.tableabc select p;
                list = query.ToList();

            }
            catch (Exception ex)
            {
               Alert.Show(ex.Message);

            }
            return list;
        }
}