开发者

Know of a good way to clean a string in .net to be used in Javascript?

I am creating a javascript confirm message in my asp.net code:

deleteButton.Attributes.Add("onclick", "javascript:return confirm('Are you sure you want to delete client " + clientName + "')"); 

The problem here is that the client name can have apostrophes and other problematic characters.

Does anyone know a good, simple way to clean the var开发者_如何学编程iable "clientName" so that I can safely use it in the javascript?

Thanks!


new JavaScriptSerializer().Serialize(clientName)


I'm not sure how to do it in .net but rule number one with user input is not to clean, but to escape it.

Otherwhise users won't be able to have " in their usernames (might not be so common but in other situations, like this response to your question i had a very legitmate reason to include a ")


I'm sure you've thought of this, but the .Replace()function is about as simple as it gets.

deleteButton.Attributes.Add("onclick", "javascript:return confirm('Are you sure you want to delete client " + clientName.Replace("'", "&_#39" + "')"); 


To get a little fancier:

    public static string ToJavascriptString(this string str)
    {
        Dictionary<string, string> replace = new Dictionary<string, string>();
        replace.Add("'", @"\'");
        replace.Keys.ToList().ForEach(s => str = str.Replace(s, replace[s]));
        return str;
    }


SecurityElement.Escape(string s)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜