首页 文章

无法使用SQL数据激活消息框 - ASP.NET

提问于
浏览
1

我正在测试我对ADO.NET和SQL的了解,目前我正在尝试做基础知识 . 我想从表中读取,当用户单击按钮时,会弹出一个消息框,其中包含ApplicationName列中的值 .

当我点击按钮时,它目前没有做任何事情......任何想法?

protected void TestSubmit_ServerClick(object sender, EventArgs e)
    {
        // Initialize the database connector.
        SqlConnection connectSQL = new SqlConnection();

        // Send the connection string.
        connectSQL.ConnectionString = @"Data Source = localhost\SQLEXPRESS;" + 
            "Initial Catalog = Inputs; Integrated Security = SSPI";

        try
        {
            // Setup our command.
            SqlCommand theCommand = new SqlCommand("SELECT * FROM Inputs", connectSQL);

            // Write the stored value in the text boxes.
            connectSQL.Open();

            SqlDataReader theReader;

            theReader = theCommand.ExecuteReader();
            theReader.Read();
            MessageBox(theReader["ApplicationName"].ToString());

            theReader.Close();
            connectSQL.Close();
        }
        catch (Exception ee)
        {
            MessageBox("Oopsie: " + ee);
        }       

 private void MessageBox(string msg)
    {
        Label lbl = new Label();
        lbl.Text = "" + Environment.NewLine + "window.alert('" + msg + "')";
        Page.Controls.Add(lbl);
    }

3 回答

  • 0

    您基本上只是将"window.alert('your message');"作为HTML发送到浏览器,这不会作为JavaScript执行 . 你真的希望它成为"popup"吗?如果是这样,请考虑使用RegisterStartupScript()而不是通过标签(http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx)输出JS . 如果没有,那么为什么不将标签的内容设置为返回消息?

  • 0

    从MSDN获取的示例并针对您的示例进行了修改

    private void MessageBox(string msg)
    {
        StringBuilder cstext2 = new StringBuilder();
        cstext2.Append("<script type=\"text/javascript\">");
        cstext2.Append("window.alert('" + msg + "')} </");
        cstext2.Append("script>");
        ClientScript.RegisterClientScriptBlock(cstype, csname2, cstext2.ToString(), false);
    }
    

    您也可以使用RegisterStartupScript而不是RegisterClientScriptBlock .

    编辑:或者经典的ASP方式也应该有效 .
    我没有任何编辑就写这篇文章 .

    Response.Write(@"<script language='javascript'>window.alert('" + msg + "');</script>");
    
  • 2

    它确实执行 . 我在其他代码中使用它,并且messagebox函数在其他项目上工作正常 .

    这是我真正想做的事情:

    try
            {
                // Setup our command.
                SqlCommand theCommand = new SqlCommand("SELECT * FROM Inputs", connectSQL);
    
                // Write the stored value in the text boxes.
                connectSQL.Open();
    
                SqlDataReader theReader;
    
                theReader = theCommand.ExecuteReader();
                theReader.Read();
                TextBox6.Text = (theReader["ApplicationName"].ToString());
    
                theReader.Close();
                connectSQL.Close();
            }
            catch (Exception ee)
            {
                MessageBox("Oopsie: " + ee);
            }
    

    请注意,TextBox6是网站上的ASP文本框 . 单击TestSubmit不显示文本 .

相关问题