Question

Suppose I'm running a site with many .aspx pages that inherit from a file called FormPage.cs. When these pages were created, many of them used hidden fields as in System.Web.UI.WebControls.HiddenField. Now, it has been realized that the Value property of these hidden fields needs something like the following:

public override string Value
{
    get
    {
        return HttpUtility.HtmlDecode(base.Value);
    }
    set
    {
        base.Value = HttpUtility.HtmlEncode(value);
    }
}

Is it possible to, in the FormPage.cs file, modify the get and set methods of HiddenField without creating a new class that inherits from it, so I won't have to replace every instance of HiddenField throughout all the pages?

Was it helpful?

Solution

You can add an extension method to your HiddenField control--it doesn't require inheritance for it to work. But the solution is also limited, since you'll have to change the code to reference the extension method by default.

public static void SetValue(this HiddenField c, string text)
{
    c.Value = HttpUtility.HtmlEncode(text);
}

public static string GetValue(this HiddenField c)
{
    return HttpUtility.HtmlDecode(c.Value);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top