如何将 ViewState 的值读入变量?

How can I read the value of a ViewState into a variable?

我在字段中声明了一个字典,例如:

Dictionary<String, string[]> operationDetails = new Dictionary<string, string[]> { };

执行了一些操作并将字典存储回 ViewState,如下所示:

ViewState.Add("operationDetails", operationDetails);

我现在想读取这个变量并将其存储回 operationDetails:

operationDetails = ViewState["operationDetails"];

然而,这个returns我遇到了无法将对象转换为字典的错误。我试过 Convert.ToDictionary 但这样的说法不存在。

如何将此视图状态读回变量?

您必须将 ViewState 转换回其原始数据类型

operationDetails = ViewState["operationDetails"] as Dictionary<String, string[]>;

这就是为什么建议使用 ViewBag 而不是 ViewState 它使您免于在视图中重新转换

set in c#   as  ViewBag.operationDetails = operationDetails;
get in razor as operationDetails =ViewBag.operationDetails