我有这样的公开名单:
public List<links> googleRec = new List<links>();
public class links
{
public string url { get; set; }
public string title { get; set; }
public string description { get; set; }
public int place { get; set; }
}
我在page_load()
中设置了这些值protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{ //googlerec get its values in page_load correctly}
}
当我想在googlerec中使用page_load外的值时,它有0条记录
foreach (links element in googleRec)
{
//googlerec has no record here
}
答案 0 :(得分:2)
您可以在会话中存储列表
Session["googleRec"] = new List<links>();
答案 1 :(得分:1)
您可以使用通常用于保存特定网页特定信息的ViewState
。
要在ViewState
活动中Page_Load()
保存您的列表
ViewState["myList"] = googleRec;
从ViewState
List<links> googleRec= (List<links>)ViewState["myList"];
如果您想了解有关ViewState
的更多信息,请参阅详细链接。
https://msdn.microsoft.com/en-us/library/ms972976.aspx
答案 2 :(得分:0)
请考虑以下示例。
代码背后:
public partial class _Default : Page
{
public List<links> googleRec = new List<links>();
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
googleRec = GetLinks();
Session["links"] = googleRec;
}
else
{
googleRec = (List<links>)Session["links"];
}
}
private List<links> GetLinks()
{
return new List<links>
{
new links {description = "new link 1", place = 1, title = "link title 1", url = "https://www.facebook.com/" },
new links {description = "new link 2", place = 2, title = "link title 2", url = "http://www.google.pl" },
new links {description = "new link 3", place = 3, title = "link title 3", url = "https://twitter.com/?lang=pl" },
};
}
}
查看:
<hr />
<div class="row">
<div class="col-md-4">
<% foreach (links item in googleRec) { %>
<div>
<%= item.title %>
</div>
<% } %>
</div>
</div>
<hr />
<asp:Button ID="sender" runat="server" Text="Do postback" />