Tuesday, November 01, 2011

ASPX data-bound values and Javascript combined - tips and tricks

There are ways at combining ASPX data bound portions of code neatly with Javascript and some of the syntax is not very memorable and can be tricky. To get a reference to a server control on the page via javascript, use the ClientID property, like so:
var grid = document.getElementById("<%= CurrApprovalsGrid.ClientID %>");
Alternatively, if you're using jQuery:
var grid = $find("<%= CurrApprovalsGrid.ClientID %>");
To pass bound values (inside 'Eval' methods) to a javascript function, the syntax is the following:
OnClientClick='<%# "if (!checkDocument(" + Eval("JobId") + "," + Eval("SubJobId") + ")) return false;" %>'
Make careful note of the extra speech marks - these must be included as is or the page will break.

To fire an ItemCommand on a server side control in a grid view - for example a LinkButton from javascript code, use the following syntax:
var masterTable = $find("<%= CurrApprovalsGrid.ClientID %>").get_masterTableView(); masterTable.fireCommand("ViewLatest", ""); // 'ViewLatest' is the name of the CommandName

No comments:

Fixes to common .NET problems, as well as information on .NET features and solutions to common problems that are not language-specific.

Fixes to common .NET problems, as well as information on .NET features and solutions to common problems that are not language-specific.

Z