Control Attributes render Encoded on dot net 4 - how to disable the encoding?

后端 未结 4 2110
深忆病人
深忆病人 2021-01-20 03:55

I have an issue in asp.net 4.

When I add an attribute on controls, then the render it encoded.

For example, when I type this code

         


        
4条回答
  •  悲哀的现实
    2021-01-20 04:09

    If you really want to prevent the encoding of parameters, you'll need to create your own customized control and override the AddAttributesToRender method. Obviously this isn't very flexible because you'll need to create a separate custom control for each type of control you use.

    Fortunately, this is very easy and only needs a few lines of code so may work out. Here is the complete code needed for a customized button:

    public class MyCustomButton : Button
    {
        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            base.AddAttributesToRender(writer);
            writer.AddAttribute("onclick", "myJavascriptFunction('a string');", false); // passing false to the AddAttribute method tells it not to encode this attribute.
        }
    }
    

    Obviously, this only appends a hard-coded onclick to the end of the attributes and may interfere if an onclick has already been provided. If you wanted to take this further, you could iterate over the actual Attributes collection and add them all this way.

提交回复
热议问题