0

在一个 aspx 页面中,我有以下转发器:

<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>

在文件后面的代码中,我有以下方法:

    protected void Page_Load(object sender, EventArgs e)
    {
        var paperID = Session["paperID"].ToString();
        QuestionPaper = repository.GetPaper(Int32.Parse(paperID));
        r.DataSource = QuestionPaper.Questions;
        r.DataBind();
    }

    protected void paper_ItemCommand(object sender, RepeaterCommandEventArgs e)
    {
        switch (e.CommandName)
        {
            case "ViewConversationsCommand":
                var hidden = e.Item.FindControl("questionID") as HiddenField;
                var myquestionID = hidden.Value;
                break;
        }
    }

我遇到的问题是,当我单击转发器上的查看对话按钮时,代码会点击page_load方法而不是我的paper_ItemCommand方法。我在这里做错了什么?

4

3 回答 3

4

发生页面加载是因为每次您点击按钮时,回发都会发生在它自身的页面上,并且它的整个页面生命周期都会运行。如果您想防止在按钮单击时不执行页面加载内容,您可以尝试如下:

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack){
      // Your existing stuff
    }
}

祝你好运 !!

于 2012-08-14T17:58:24.883 回答
2

每次加载页面时,包括当您回发到页面时(例如,通过单击 a Button),Page_Load都会触发事件处理程序。关键是检查Page对象的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();
    }
}
于 2012-08-14T17:58:23.817 回答
1

page_load 总是先运行 http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon/html/vbconwebformspageprocessingstages.asp 测试如果不是回发设置你的初始化

if(!Page.IsPostback)
{
 var paperID = Session["paperID"].ToString(); 
        QuestionPaper = repository.GetPaper(Int32.Parse(paperID)); 
        r.DataSource = QuestionPaper.Questions; 
        r.DataBind(); 
}
于 2012-08-14T18:01:15.147 回答