函数使用双引号,但不能使用单引号

问题描述 投票:0回答:1

我正在使用Webforms开发页面,而我的aspx.cs页面有问题。我有一个带有值的树视图,这些值应该用作gridview(sqlServer数据库)的过滤器。我将选中的节点保存在字符串中,并且代码使用双引号可以正常工作,但是当我使用单引号(需要)时,运行它不会发生任何事情。

这是我正在运行的代码。我使用ClientScript只是为了查看保存的字符串。下面的代码不起作用,如果我将'替换为',它可以工作,但是我不能用它来过滤sql表。想法?

protected void Submit(object sender, EventArgs e)
        {
            string exp1 = string.Empty;
            foreach (TreeNode node in Source_TreeView.CheckedNodes)
            {
                if (node.Checked)
                {
                    if (exp1 != string.Empty)
                    {
                        exp1 += " OR ";
                    }
                    exp1 += "Source=" + "'" + node.Value + "'";
                }
            }
            if (exp1 != string.Empty)
            {
                exp1 = "(" + exp1;
                exp1 = exp1 + ")";
            }
            exp1 = exp1.Replace("'", "''");
            string exp2 = string.Empty;
            foreach (TreeNode node in Sink_TreeView.CheckedNodes)
            {
                if (node.Checked)
                {
                    if (exp2 != string.Empty)
                    {
                        exp2 += " OR ";
                    }
                    exp2 += "Sink=" + "'" + node.Value + "'"; 
                }
            }
            if (exp2 != string.Empty)
            {
                exp2 = "(" + exp2;
                exp2 = exp2 + ")";
            }
           ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + exp1 + exp2 + "');", true);
        }
c# asp.net webforms quotes
1个回答
0
投票

这不起作用,因为您的字符串exp1或exp2中的一个包含简单的引号。因此,当您使用RegisterStartupScript发送脚本时,可能会出现Javascript错误。检查控制台

尝试使用\“

string yourScript  = string.format("alert(\"{0} {1}\");", exp1, exp2)
ClientScript.RegisterStartupScript(this.GetType(), "alert", yourScript, true);
© www.soinside.com 2019 - 2024. All rights reserved.