如何在ASP.NET标签内显示时转义撇号

时间:2015-03-11 18:18:56

标签: c# asp.net

我有以下函数截断SQL Server varchar列并将其添加到字符串中:

public void Pp()
{
    strSql = @""; //query
    using (SqlConnection conn = new SqlConnection(gstr))
    {
        try
        {
            SqlDataAdapter da = new SqlDataAdapter(strSql, conn);

            myDataSet = new DataSet();
            da.Fill(myDataSet);

            string specific = "";
            string generic = "";
            string strTemp = "";

            foreach (DataRow r in myDataSet.Tables[0].Rows)
            {
                if (r["MessageText"].ToString().Length <= 65)
                {
                    strTemp = r["MessageText"].ToString();
                }
                else
                {
                    strTemp = TruncateLongString(r["MessageText"].ToString(), 65);
                }
                specific += "</b><span class='hoverText' title='" + r["MessageText"] + "'>" + strTemp + "...</span>";
                strTemp = "";
            }

            lblMessage.Text = "<b>SPECIFIC MESSAGES:</b> <br />" + specific;
        }
        catch (Exception ce)
        {
        }
    }
}
public string TruncateLongString(string str, int maxLength)
{
    return str.Substring(0, maxLength);
}

如果r["MessageText"]包含一个appostrophe,它会切断后面的任何内容。 (全文:no way no way HERE we go again but this is not working. Is it? or Is it not? I can't be too sure though. Can someone please check.

以下是实时预览的示例(显示title但由于撇号而被切断):

enter image description here

这是源码(撇号显示在紫色框中。由于撇号,颜色编码也没有出现问题,这意味着代码不正确):

enter image description here

如何确保它不会转义任何转义字符,例如'/\

2 个答案:

答案 0 :(得分:4)

您需要先对HTML进行编码。

致电this.Server.HtmlEncode( str )。这也可以防止其他特殊字符,例如&<

也就是说,您使用单引号作为属性分隔符,但HtmlEncode只编码双引号,因此您需要将代码更改为:

specific = String.Format( CultureInfo.InvariantCulture, @"</b><span class=""hoverText"" title=""" + this.Server.HtmlEncode( r["MessageText"] ) + """>" + strTemp + @"...</span>";

答案 1 :(得分:1)

.Replace(“'”,“\\'”);你可能也想用双引号做同样的事。