ASP.NET single quotes are converted to '

后端 未结 6 1382
我在风中等你
我在风中等你 2021-01-02 02:24

Note: Most probably this will be a double question, but since I haven\'t found a clear answer, I\'m asking it anyway.

In ASP.NET I\'d like to add some JavaScript to

6条回答
  •  北荒
    北荒 (楼主)
    2021-01-02 02:57

    In case someone else finds this question, this is the way I was able to inject attributes from a custom control without having the values html encoded. This is an example of a button that calls out to an async function to confirm an button press action.

    The key is to use the writer.AddAttribute() which has the flag to disable the HTMLEncode step. This also seems to be dependent on which version of asp.net you are using. this works in .net 4.6.1

     public class ConfirmationLinkButton : LinkButton
    {
        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            base.AddAttributesToRender(writer);
            string script = "confirmAsync('" + ConfirmationMessage.Replace("'", "\\'") + "', " + Callback() + ");" +
                            "return false;";
            writer.AddAttribute(HtmlTextWriterAttribute.Onclick, script, false);
        }
    
        private string Callback()
        {
            return "(data) => { if (data===true) {" + Page.ClientScript.GetPostBackEventReference(this, "") + "}}";
        }
    
        public string ConfirmationMessage { get; set; }
    }
    

提交回复
热议问题