Search code examples
asp.netservercontrols

change div into html server control and add an click event


I have a piece of code

<div class="class1">
 <span>testing</span>
</div>

I will change this into html server control.

<div class="class1" id="div1" runat="server">
 <span>testing</span>
</div>

I want to add a click event.

<div class="class1" id="div1" runat="server" onclick="Test_Click">
 <span>testing</span>
</div>

On code behind, I have that event handler.

protected void Test_Click(object sernder, EventArgs e)
{
  //code
}

But it is not working.. I tried by changing onclick to onserverclick. it is still not working..

Any other way?


Solution

  • From your post I got that you want to simple go to the server side event while clicking the Div. You can't directly give this to a DIV, instead you can use a Hidden Button in the div and trigger the click event manually.

        <script>
        function clickDiv() {
        if (__doPostBack) {
            __doPostBack('<%=btnNew.UniqueID %>', '');
        }
        else {
            var theForm = document.forms['aspnetForm'];
            if (!theForm) {
                theForm = document.aspnetForm;
            }
            if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
                theForm.__EVENTTARGET.value = '<%=btnNew.UniqueID %>';
                theForm.__EVENTARGUMENT.value = '';
                theForm.submit();
            }
        }
    }
        </script>
    
    <div class="class1" id="div1" runat="server" onclick="clickDiv()">
     <span>testing</span>
    <asp:Button runat="server" Style="display: none" ID="btnNew" Text="Submit" OnClick="btnNew_Click" /> 
    </div>
    

    In _Default.aspx.cs

    public partial class _Default : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
    
    
            }
    
            protected void btnNew_Click(object sender, EventArgs e)
            {
                result.Text += "hey, event handler! ";
            }
    
    
        }
    

    You can see the jQuery Implementation over here: JQuery UI Dialog & Asp (web forms) calling event handler