c# - 按钮点击随机工作 asp.net

标签 c# asp.net button postback

我的 asp.net 网页上有一个 RadMultipage 控件。

我将用户控件加载为该控件内的页面。

下面是加载用户控件的代码。

 protected void RadMultiPage1_PageViewCreated(object sender, Telerik.Web.UI.RadMultiPageEventArgs e)
    {
        try
        {
            string controlName;
            int index = e.PageView.ID.Trim().IndexOf(" ");
            if (index > 0)
            { controlName = e.PageView.ID.Trim().Remove(index); }
            else
            { controlName = e.PageView.ID; }

            Control pageViewContents = LoadControl(controlName + ".ascx");
            pageViewContents.ID = e.PageView.ID + "userControl";
            e.PageView.Controls.Add(pageViewContents);
        }
        catch (Exception ex)
        {
            Utility.WalkException(this, ex, "There was an error while performing this operation.");
        }
    }

我还启用了 View 状态和 autoeventwireup。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" EnableViewState="true" ViewStateMode="Enabled" Inherits="VentureAssessmentApp.Default" %>

现在我遇到的问题是用户控件上的按钮。该按钮的点击事件没有被触发。它只是重新加载页面。甚至 IsPostBack 也返回 false。

任何人都可以提出一些解决方案吗?碰巧有时点击事件起作用,而大多数时候不起作用。

最佳答案

这是一个典型的页面生命周期问题。我猜发生的事情是,当回发被触发时,页面不知道哪个控件触发了回发,因为当它进行评估时,Button(及其父 UserControl)尚未添加到页面的控件层次结构中...因此,我将手指指向 RadMultiPage1_PageViewCreated 事件处理程序。在我看来,将服务器控件动态添加到页面是一个尴尬的地方。

建议

将控件加载逻辑移出 RadMultiPage1_PageViewCreated 事件。将此逻辑放在页面的 Init 事件中,或者如果 Init 事件太早,则放在页面的 Load 事件中。

您可以通过检查 SelectedIndex 属性或 SelectedPageView 属性来确定在 RadMultiPage 控件中选择了哪个页面。但是,如果您将 RadTabStrip 控件与 RadMultiPage 控件结合使用,您可以检查 RadTabStripSelectedTabSelectedIndex 属性

例子

protected override void OnLoad(EventArgs e)
{
    LoadStuff();
}

private void LoadStuff()
{
        try
        {
            string controlName;
            int index = YOUR_MULTI_PAGE_CONTROL.SelectedIndex;
            if (index > 0)
            { controlName = YOUR_MULTI_PAGE_CONTROL.PageViews[index].ID.Trim().Remove(index); }
            else
            { controlName = YOUR_MULTI_PAGE_CONTROL.PageViews[index].ID; }

            Control pageViewContents = LoadControl(controlName + ".ascx");
            pageViewContents.ID = YOUR_MULTI_PAGE_CONTROL.PageViews[index].ID + "userControl";
            YOUR_MULTI_PAGE_CONTROL.PageView.Controls.Add(pageViewContents);
        }
        catch (Exception ex)
        {
            Utility.WalkException(this, ex, "There was an error while performing this operation.");
        }
}

关于c# - 按钮点击随机工作 asp.net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24526638/

相关文章:

c# - 对象的惯用 C# 仅通过注册到事件进行交互

C# 阻塞等待响应

c# - 在 onclientclick 中将变量传递给 javascript

c# - Fedex 服务集成错误(无法生成临时类)

html - 如何消除具有相对位置的按钮上的死区? (HTML/CSS)

c# - Windows Kinect SDK + OpenNI Primesense

asp.net - 更改用户名 ASP.net MVC 3 成员资格

facebook - 如何制作一个非常大的 facebook 分享按钮?

CSS 图像按钮不正确

c# - C# 中的 SVN 框架