2

クラス「Service」を使用してDBに接続し、DataTableをASP.NETページに返します。

SqlExceptions をキャッチするために try/catch を使用しています。アラート ボックスに例外テキストを表示したいと考えています。どうすればいいですか?

これは Service.class の私の関数です:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Classes
{
    public class Service
    {
        private static DataTable getDataTable(string query)
        {
            DataTable dt = null;
            SqlConnection con = Dao.getConnection();
            if (Dao.checkConnection())
            {
                SqlDataAdapter da = new SqlDataAdapter(query, con);
                dt = new DataTable();
                try
                {
                    da.Fill(dt);
                }
                catch (SqlException ex)
                {
                //MessageBox.Show(ex.Message);
                Response.Write("<script>alert('This is Alert');</script>");
                //HttpContext.Current.Response.Write();
                //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), " ","alert('ERROR')", true);
                //var clientScript = Page.ClientScript;
                //clientScript.RegisterClientScriptBlock(null, "AlertScript", "alert('ERROR')'", true);
                //System.Diagnostics.Debug.WriteLine("Database error: " + ex.Message);
            }
        }
        return dt;
    }

コンパイラはこれを教えてくれます: 「Response」という名前は現在のコンテキストには存在しません。

かなり基本的なことだと思いますが、まだ答えを見つけることができていません。コメントされたものは、私がこれまでに試したことです!

4

2 に答える 2

1

System.Web.HttpContext.Current.Responseを使用できます。探している Response は System.Web.UI.Page から継承するクラスで利用可能です。

System.Web.HttpContext.Current.Response.Write("<script>alert('This is Alert');</script>")
于 2013-04-06T18:04:12.023 に答える
0

これを試して

ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + String Exception message + "');", true);
于 2013-04-06T18:27:43.607 に答える