Table row onclick event that runs codebehind

纵饮孤独 提交于 2019-12-06 07:50:37

Using jQuery you can do the following and trigger a postback:

<table>
    <tr id="1">
        <td>AAA</td>
        <td>BBB</td>
        <td>CCC</td>
    </tr>
    <tr id="2">
        <td>AAA</td>
        <td>BBB</td>
        <td>CCC</td>
    </tr>
    <tr id="3">
        <td>AAA</td>
        <td>BBB</td>
        <td>CCC</td>
    </tr>
</table>

<script type="text/javascript">
    $(function () {
        $("table tr").click(function (e) {
            //alert the row index that was clicked
            alert($("table tr").index(this));

            //alert the id of the row
            alert($(this).attr("id"));

            //submit the form...
        });
    });
</script>

OR use the onclick event of the row...

<tr onclick="doPostBack('<%#DataBinder.Eval(Container.DataItem, "id") %>')">

...and trigger a javascript function.

<script type="text/javascript">
    function doPostBack(id)
    {
        //submit form
    }
</script>

You could make your page (or control, if that's inside a control) implement IPostBackEventHandler interface and use ClientScriptManager.GetPostBackEventReference method (using Page.ClientScript propery to get a reference to ClientScriptManager) to get a js-method-call-string which will make a postback to your page. As a control argument to GetPostBackEventReference method use your page. Then set onclick property of tr to that js-method-call-string.


Example

In aspx:

<table>
    <tr onclick="<%= _jsPostBackCall %>;">
        <td>a</td>
        <td>b</td>
        <td>c</td>
    </tr>
</table>

<h1>
    <asp:Literal ID="litMessage" runat="server" />
</h1>

In codebehind:

public partial class _Default : System.Web.UI.Page, IPostBackEventHandler
{
    protected String _jsPostBackCall;

    protected void Page_Load(object sender, EventArgs e)
    {
         // "myTr" will be passed as an argument to RaisePostBackEvent method
        _jsPostBackCall = ClientScript.GetPostBackEventReference(this, "myTr");
    }

    public void RaisePostBackEvent(string eventArgument)
    {
        switch (eventArgument)
        {
            case "myTr":
                HandleTrClick();
                break;

            // you can add other controls that need postback processing here

            default:
                throw new ArgumentException();
        }
    }

    private void HandleTrClick()
    {
        litMessage.Text = "Tr clicked.";
    }
}

You can simply use

__doPostBack(eventName, eventArgs); 

Here eventName is code-behind event handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!