C#ASP.NET用户控件如何处理div点击服务器端?

Mar*_*ijn 6 c# asp.net user-controls

我正在创建一个用户控件.用户控件是一个div,我想向它添加一个click事件.

编辑:

对其具有此控件的页面必须处理此事件.

我怎样才能做到这一点?

roc*_*cka 9

首先,您需要在您的上定义一个UserControl允许Page包含UserControl注册和处理事件的事件.例如:

public partial class MyUserControl : System.Web.UI.UserControl
{    
    // Event for page to handle
    public event EventHandler DivClicked;

    protected virtual void OnDivClicked(EventArgs e)
    {
        if (DivClicked != null)
            DivClicked(this, e);
    }        

    protected void Page_Load(object sender, EventArgs e)
    {
        // Page Load Code goes here
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:如果您使用支持回发的控件,则下一部分会更容易.但是,既然你想使用a div,我将解释如何强制div进行回发.我要感谢Mathew Nolton的解决方案.

所以,在你需要的Page_Load方法中UserControl添加一个onClick属性来调用ASP.NET的__doPostback()javascript函数,该函数为你的服务器调用服务器div.这使得div能够回发到服务器.此外,以确定哪些控制由于回发,我提供的divClientId一些码元一起从其他控件区分我的回发.请记住,当您div在.ascx文件上定义时,它必须具有已id分配和设置runat="server",以便在服务器端可访问.

好的,现在通过添加一个onclick属性div,它会在点击它的任何时候回发到服务器.因此,当回发导致Page_Load被调用时,我检查是否是div导致回发的.如果是这样,我提出要由Page处理UserControlDivClicked事件.

public partial class MyUserControl : System.Web.UI.UserControl
{
    // Event Definition and Raising methods
    ...

   protected void Page_Load(object sender, EventArgs e)
   {
       // @@@@ will denote this is an argument I provided.
       string arg = "@@@@" + divClickableDiv.ClientID;
       // Add postback method to onClick 
       divClickableDiv.Attributes.Add("onClick", 
       Page.ClientScript.GetPostBackEventReference(divClickableDiv, arg));

       if (IsPostBack)
       {
           // Get event arguments for post back.
           string eventArg = Request["__EVENTARGUMENT"];

           // Determine if postback is a custom postback added by me.
           if (!string.IsNullOrEmpty(eventArg) && eventArg.StartsWith("@@@@"))
           {
               // Raise the click event for this UserControl if the div
               // caused the post back.
               if (eventArg == arg) 
                   OnDivClicked(EventArgs.Empty);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这应该是为了做UserControl,现在你要做的就是DivClicked在页面上注册活动.

不幸的是,您不会获得设计时间支持来注册活动.但是,您仍然可以将代码添加到.aspx页面.在您放置的页面上,UserControl向被UserControl调用者添加属性,OnXXX其中XXX是名称事件.所以,对于我上面的例子,我会UserControl在页面上定义我的样子:

<uc1:MyUserControl  ID="MyUserControl1" runat="server" OnDivClicked="MyUserControl1_DivClicked" />
Run Code Online (Sandbox Code Playgroud)

现在,您将处理程序代码添加到代码Page隐藏文件中(假设您使用的是代码隐藏),如下所示:

public partial class MyPage : System.Web.UI.Page 
{
    // Called whenever div in MyUserControl is clicked.
    protected void WebUserControl1_DivClicked(object sender, EventArgs e)
    {
        // Handle Div click event here.
    }
}
Run Code Online (Sandbox Code Playgroud)

应该这样做.我希望这篇文章可以帮到你.