C# 中继器按钮发回页面加载而不是我的方法?
在aspx页面中,我有以下中继器:C# 中继器按钮发回页面加载而不是我的方法?,c#,asp.net,.net,C#,Asp.net,.net,在aspx页面中,我有以下中继器: <asp:Repeater runat="server" ID="r" OnItemCommand="paper_ItemCommand"> <ItemTemplate> <div style="padding-bottom:20px"> <asp:HiddenField runat="server" ID="questionID" Value='<%# Eval(
<asp:Repeater runat="server" ID="r" OnItemCommand="paper_ItemCommand">
<ItemTemplate>
<div style="padding-bottom:20px">
<asp:HiddenField runat="server" ID="questionID" Value='<%# Eval("ID") %>'/>
<asp:Label runat="server" ID="questionNumber" Text='<%# Eval("Number") %>'/><br />
<asp:Label runat="server" ID="question1" Text='<%# Eval("Question1") %>' /><br />
[ <asp:Label runat="server" ID="questionMark" Text='<%# Eval("Mark") %>'/> ]<br />
<asp:Button ID="View_Conversations" runat="server" Text="View Conversations" CommandName="ViewConversationsCommand" />
</div>
</ItemTemplate>
<SeparatorTemplate>
<hr />
</SeparatorTemplate>
</asp:Repeater>
我遇到的问题是,当我单击中继器上的View Conversation按钮时,代码会点击page\u load方法,而不是paper\u ItemCommand方法。我这里出了什么问题?每次加载页面时,包括当您发回页面时(例如,通过单击按钮),页面加载事件处理程序都会被点击。关键是检查页面对象的IsPostBack属性:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// do things that only should be done on the first page load
var paperID = Session["paperID"].ToString();
QuestionPaper = repository.GetPaper(Int32.Parse(paperID));
r.DataSource = QuestionPaper.Questions;
r.DataBind();
}
}
页面加载之所以发生,是因为每次点击按钮时,回发都会发生在页面上,页面本身及其整个页面生命周期都会运行。如果要防止不执行“页面加载”按钮,请单击,您可以尝试以下操作:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack){
// Your existing stuff
}
}
祝你好运 页面加载始终首先运行 如果没有回发,则测试设置初始化
if(!Page.IsPostback)
{
var paperID = Session["paperID"].ToString();
QuestionPaper = repository.GetPaper(Int32.Parse(paperID));
r.DataSource = QuestionPaper.Questions;
r.DataBind();
}
if(!Page.IsPostback)
{
var paperID = Session["paperID"].ToString();
QuestionPaper = repository.GetPaper(Int32.Parse(paperID));
r.DataSource = QuestionPaper.Questions;
r.DataBind();
}