I've added some jQuery to a widget so that the table the widget renders can be striped on the client. The code is shown below. Everything works fine when the widget is initially displayed, but should the user refresh the widget, the jQuery code does not run on refresh and the table loses its css styling. Either this is because the script should not be inside the update panel, or its because of some other reason related to the Microsoft Ajax Library.
I suppose this more generally can be summarized as "How do you get JavaScript code to run on the client when an update panel is refreshed?". On the server side, it would be cool if I could attach something to the update panel which will get run automatically on the client when that single instance of the update panel gets refreshed.
I've not been able to find a clear answer. I've done more MVC than Web Forms and I'm not that experienced with the Microsoft Ajax Library either server or client side. Some say that there is a general "update panel refreshed" event that can be hooked on the client to run code when any update panel is refreshed, but there are two problems. In a dynamic dashboard, update panels come and go as the user adds and removes widgets - the page structure is not fixed, and not known until runtime. The second problem is how would a single handler distinguish between two instances of the same widget on the page, given that widgets are not single instance.
To get the colorization, I could revert to static CSS attributes; I'll probably do that anyway, but that still leaves the table row striping and sort-by-header click that requires the jQuery table sorter.
Please could someone provide a detailed example of how to solve this, as it's going to be a problem most developers run into when developing widgets.
Code:
<asp:UpdatePanel ID="updatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Table ID="infoTable" runat="server" GridLines="Both" Width="295px" />
<script type="text/javascript">
//<![CDATA[
$(document).ready(function () {
var infoTableId = "<%= infoTable.ClientID %>";
var $infoTable = $("#" + infoTableId);
$infoTable.tablesorter();
$infoTable
.bind("sortStart", function () {
$infoTable.find("tbody tr").css("background-color", "#FFFFFF");
})
.bind("sortEnd", function () {
$infoTable.find("tbody tr:odd").css("background-color", "#FFFFFF");
$infoTable.find("tbody tr:even").css("background-color", "#EDEDED");
});
$infoTable.find("thead th").css({ "background-color": "#368DDE", "color": "#FFFFFF", "padding": "2px", "cursor": "pointer" });
$infoTable.find("tbody tr:odd").css("background-color", "#FFFFFF");
$infoTable.find("tbody tr:even").css("background-color", "#EDEDED");
});
//]]>
</script>
</ContentTemplate>
</asp:UpdatePanel>