c# - asp.net + Viewstate 和逗号分隔的字符串

标签 c# asp.net viewstate

我读过很多关于页面如何因过度使用 Viewstate 而陷入困境的文章,我不确定是否使用逗号分隔的字符串(可能为 3 - 4 个单词)并将其拆分为数组

string s = 'john,23,usa';
string[] values = s.Split(',');

检索将有所帮助,因为我看到我的许多同事正在这样做,大概是为了提高页面加载性能。任何人都可以建议吗?

最佳答案

实际上,它在某些情况下确实有所作为,但它看起来很棘手,而且往往无关紧要。
见以下案例:

示例显示了 ViewState 的大小(以字节为单位),这意味着没有任何内容的页面会产生 68 字节的 ViewState。 其他所有内容都是手动加载到 ViewState 的内容。

将字符串值 0..9999 放在 ViewState 上。

string x = string.Empty;

for (int i = 0; i < 10000; i++)
{
    if (i != 0) x += ",";

    x += i;
}

//x = "0,1,2,3,4,5,6,7,8...9999"
ViewState["x"] = x;

//Result = 65268 bytes

还有一个数组:

string[] x = new string[10000];

for (int i = 0; i < 10000; i++)
{
    x[i] = i.ToString();
}

ViewState["x"] = x;

//Result = also 65268 bytes

当在可覆盖的 SaveViewState 方法上返回时,上述两种情况都会产生 65260 字节的 ViewState。比将其加载到 ViewState 对象上少 8 个字节。

但是,在其他一些情况下:

//104 bytes
ViewState["x"] = "1,2,3,4,5,6,7,8,9,10" 

// 108 bytes
ViewState["x"] = new string[] { "1", "2", "3" , "4", "5", "6", "7", "8", "9", "10"} 

如果重写页面的SaveViewState 方法:

protected override object SaveViewState()
{
    //100 bytes
    return new string[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };

    //100 bytes
    return "1,2,3,4,5,6,7,8,9,10";
}

由于 ViewState 是加密的并且是 Base64 编码的, 在某些情况下,它可能只是对两个不同的对象进行字符串编码,从而为页面生成两个不同的输出。

关于c# - asp.net + Viewstate 和逗号分隔的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15178003/

相关文章:

c# - 来自数据库的视频流

asp.net - Viewstate - 完全困惑。

c# - 随机出现

c# - 使用 Visual Studio Code 在构建时复制内容文件

c# - 如何仅在 EF Core 中包含相关表的最新记录

javascript - 使用 JavaScript 启用/禁用单选按钮列表

c# - 如何代码重用apsx?

asp.net - 间歇性 "Failed to load viewstate"错误

asp.net - 为什么我的 @page enableviewstate 没有覆盖 web.config 中页面的 EnableViewstate?

c# - 在 C# 中检查 CSV 文件是否为 DOS-CSV