Using jQuery.ajax with ASP.NET Update Panel

The UpdatePanel in ASP.NET is a useful tool that prevents you from having to refresh the whole page for each server request. It uses the script manager to make ajax requests to the server. This all works well on simple pages with a few controls, but things get can get messy quick when dealing with more complex UI designs. It gets especially messy when your UI design involves a lot of JavaScript to enhance the UX. You may find that your JavaScript behaves unexpectedly when the UpdatePanel refreshes.

For one of my current projects I am using a Bootstrap based theme and the modal form component to display a form to edit some data. The modal uses ASP.NET user controls to generate the inputs, and for static controls this works fine. However, I need two dropdowns with one dropdown driving the selections for the second. I could simply make the first dropdown postback to the server and then update the list in the second dropdown. But since it is in a modal window that was opened with JavaScript, the postback event causes the window to close. Now you could simply use the ScriptManager top open the window back up after the postback but that looks sloppy and would likely confuse the user.

One way around this is to use jQuery to make an AJAX request to the server and update the the second dropdown independenty from the Update Panel. The following paragraphs will illustrate how to do this.

In this example I use a simple WebMethod in the code behind file but using WebAPI or WCF would likely be a more robust solution for a production application.

Here is the markup for the two controls we are binding together:

The data binding for cboCategory takes place when the form loads. The cboType will need to be populated dynamically based on the selected category.

that leads us to the JavaScript...

First, we set up an event handler for the cboCategory dropdown by using the jQuery change() method. Next, we get the selected value and pass that to the loadTypeList() function. The loadTypeList function then uses the jquery ajax() method to return the type list from the WebMethod in the code behind file.

That WebMethod looks like this...

Did you notice there is no code serializing the list to JSON? That's because ASP.NET handles this automatically for us. All we have to do is indicate a return type and the method will return valid JSON. Returning List<object> could also work here if we wanted to return an anonymous type from the LINQ query.

Isn't that cool how simple it is to bind client-side controls to server-side controls?

comments powered by Disqus