I've inherited an ASP.NET project that has poorly designed HTML; in one section, the tags are wrapped with an tag to allow for "click the row to view the information" functionality. The code is:
<asp:LinkButton ID="ViewArticle" runat="server" CommandName="Navigate" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "id") %>' >
<tr runat="server" class="list_item">
<td>some data</td>
<td>some data</td>
<td>some data</td>
</tr>
</asp:LinkButton>
I'd like to do something like:
<tr runat="server" class="list_item" onclick="doRowPostbackFunction('<%# DataBinder.Eval(Container.DataItem, "id") %>');">
<td>some data</td>
<td>some data</td>
<td>some data</td>
</tr>
How do I go about tying a JavaScript "onclick" event to the codebehind?
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
来源:https://stackoverflow.com/questions/5419115/table-row-onclick-event-that-runs-codebehind