0

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?

4

1 回答 1

0

我还会考虑创建自己的自定义控件,这很容易做到。你可以这样做:

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


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

}

由于功能非常简单,因此这是一个灵活的解决方案,因为它使您可以更全面地访问所有文本。例如,稍后如果您意识到您想要粗体文本,您不必更新控件的所有标记,您可以更改您的自定义类。这样做有很多好处。您需要做的就是<pages>在配置文件的元素中添加对命名空间/程序集的引用(带有 c 的 tagPrefix),并将标记更改为:

<c:MyLiteral Text="xyz" runat="server" />
于 2013-08-05T17:42:10.013 回答