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

后端 未结 4 2104
深忆病人
深忆病人 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.

    0 讨论(0)
  • 2021-01-20 04:13

    From MSDN WebControl.Attributes Property Documentation...

    Note

    You cannot add client-side script to a WebControl instance using the Attributes collection. To add client-side script, use the ClientScript property on the Page control.

    The problem is that Attributes expects data if it's being set in the code-behind.

    The solution is to send back a client script with your client side handler functions then you may set the attribute with the name of your functions.

    If your javascript is static, then things are even simpler, since you can send them in a script tag long before the controls are registered.

    0 讨论(0)
  • 2021-01-20 04:26

    I ran into this problem with an MvcHtmlHelper for an autocomplete.

    I ended up using |~| instead of ', and then replacing that with ' after Html.TextBox had rendered the string, but before we returned it.

    That's a really annoying "security" feature.

    0 讨论(0)
  • 2021-01-20 04:31

    Have you tried using this new ASP.NET 4 feature to make a custom encoder?

    0 讨论(0)
提交回复
热议问题