Question

I've been working on ASP.NET for just over a year now, and I've come upon an interesting thought that I'd like feedback on.

I've noticed that Literal controls save their text value in the viewstate. This seems somewhat odd to me, as it effectively ensures that whatever content is stored in the Literal control will be duplicated (once on the rendered page and once hidden within the viewstate).

As an alternative, I've begun using generic html controls with a runat="server" and the innerhtml/innertext properties. This seems to me to to achieve the same thing as literal control without the viewstate bloat provided you need to wrap your content within a tag anyway. Before I go through and eliminate as many of the Literals in my project as possible, though, I'm wondering if there is there any drawback that I'm not thinking of. Thoughts?

Was it helpful?

Solution

I would also consider creating your own custom control, which would be very easy to do. You could do:

public class MyLiteral : WebControl
{
    public string Text { get; set; }


    protected override void Render(HtmlTextWriter writer)
    {
        writer.Write(this.Text);
    }

}

Since the functionality is pretty simple, this is a flexible solution because it gives you more global access to all the texts. For instance, later if you realize you wanted bold text, you don't have to update all of the markup of the controls, you can change your custom class. There are a lot of benefits to doing it this way. All you need to do is add a refernce to the namespace/assembly within the <pages> element of the configuration file (with a tagPrefix of c), and change the markup to:

<c:MyLiteral Text="xyz" runat="server" />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top