Can I call a code behind function from a div onclick event?

前端 未结 3 927
余生分开走
余生分开走 2020-12-21 07:42

I have a bunch of divs on my page that are added at run time dynamically. When any of the dynamically added divs are clicked - All need to call the same function in my code

相关标签:
3条回答
  • 2020-12-21 08:02

    With the help from the link posted by @Tim Schmelter I tried following. This is wonderful:

    Markup:

    <div id="div1" runat="server" style="height:100px;width:100px;">click me</div>
    

    Code:

    public class MyPage  
          Inherits System.Web.UI.Page
          Implements IPostBackEventHandler
    
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        div1.Attributes("onclick") = 
             Me.Page.ClientScript.GetPostBackEventReference(Me, "div1_clicki")
    End Sub
    
    Protected Sub Div1_Click()
        'do your stuff
        div1.InnerHtml="div1 clicked"
    End Sub
    
    
    'Private Members As IPostBackEventHandler
    Public Sub RaisePostBackEvent1(ByVal eventArgument As String) Implements 
                        IPostBackEventHandler.RaisePostBackEvent
        If eventArgument = "div1_click" Then
                div1_click()
            End If
        End If
    End Sub
    
    0 讨论(0)
  • 2020-12-21 08:07

    I'm not used to write VB code so my example is in C# but maybe it can help you get started. It's probably not the cleanest way to implement this, but i'll give it a try:

    HTML

     <div id="div_Footer" class="HoverEdit" title="Click To Edit" runat="server" onclick="EditDiv(this)">
            Footer Controls and stuff go here
        </div>
    

    Client

    <script type="text/javascript">
    function EditDiv(s,e){
    var id = $(s).attr("id");
    __doPostBack(id,id);
    }
    </script>
    

    Server

    private void Page_Load(object sender, EventArgs e)
    {
       var arg = Request.Form["__EVENTTARGET"]; 'this will be empty on your first page request, but if the user click a div it will cause a postback to server, so this event will be fired again and will contain the div ID.
    
       if(arg != null)
       {
          string divID = (string)arg;
          'call your method with the argument.
       }
    }
    

    More information about this can be found here:

    http://wiki.asp.net/page.aspx/1082/dopostback-function/

    0 讨论(0)
  • 2020-12-21 08:07

    You can create a postback from javascript. One way is to make a button or linkbutton and add click event to it. Add Style="Display:none;" and force Div to postback on button click like.

    <div id="div_Footer" class="HoverEdit" title="Click To Edit" runat="server" onclick="EditDiv(this)">
        Footer Controls and stuff go here
    </div>
    //Javascript
    function EditDiv()
    {
       // do your code
       __doPostBack('ButtonAID','')
    }
    

    A nice explanation can be found in below article. ASP.NET postback with JavaScript

    0 讨论(0)
提交回复
热议问题