Archive for May, 2010

How to Manipulate the DOM before postback

Much frustration has arisen from the fact that changes made to the DOM in the initializeRequest method are not reflected on the server side. The problem is, the ViewState has already been wrapped up at this stage, and there is no other upstream method from initializeRequest.

There is a way around this problem, however. The answer is to simply cancel the postback, make your changes, and relaunch the postback. This causes the ViewState to be wrapped up after your new postback is initiated.  Here’s the code:

Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(initializeRequest);

var bSecondPass = false;

function initializeRequest(sender, args){
if(!bSecondPass){
//
//make your changes to the DOM here
//
var prm = Sys.WebForms.PageRequestManager.getInstance();
bSecondPass = true;
prm.abortPostBack();
args.set_cancel(true);
__doPostBack(args.get_postBackElement().id, document.getElementById(“__EVENTARGUMENT”).value);
}else{
bSecondPass = false;
}
}

I’ll soon be writing an article on how this can be used to make the TinyMCE rich text editor play nice with ASP.Net Ajax UpdatePanels.  I’ve written a nice little TinyMCE Asp.Net Plugin that I’m going to package up and share with you guys.  Stay tuned!

Databind a Strongly Typed List to a ListView

I tirelessly searched Google for a way to databind a strongly typed list to an Asp.Net ListView control without any good results, so now that I’ve figured this out, I thought I’d post it for the sake of others in the same boat.  This is really very simple.

From what I can tell there is no Design View support for DataBinding to a ListView.

You can, however, bind the ListView from the code behind, which I believe is a lot cleaner anyway.

List<string> lSampleList = new List<string>();
lvMyListView.DataSource = lSampleList;
lvMyListView.DataBind();

<asp:ListView ID=”lvMyListView” runat=”server”>
<ItemTemplate>
<%# Container.DataItem %>
</ItemTemplate>
</asp:ListView>


Notice that there’s no need to use the Eval() method, because there’s only one value we can get at.  Therefore You must use the Container.DataItem property instead.  Hope this helps!
Return top

__doPostBack Site Info

A discussion of ASP.Net Ajax design patterns and best practices.