Ensuring Variable Integrity in Async Callback Functions with JavaScript Closures.

Callback functions to asynchronous requests may need to reference variables outside of itself. This can be problematic because those variables might not maintain the values you expect by the time the callback function fires. In the past I’ve dealt with this by writing my code as a string, concatenating my variable values, then using eval on it in the callback. I never liked this technique because it seemed amateur, risky and unreliable for complex scenarios. Recently I came across a clever solution that seems to work quite well:
Here we wrap a function around the code, and execute it immediately passing the target variables into it. In my example the variables are file and uploader. Next, we then have an inner function that keeps the meat of our code from being executed immediately. It will be executed in the callback of the asynchronous process…but can reference the variables passed to it’s wrapper function. In the example I have used the same variable names again (no need to change them). I believe the technique duplicates the variables into a local scope where its values can be maintained. This is also known as a JavaScript Closure where functions have access to private variables that nothing else can touch or modify.

Here is a FIDDLE showcasing the technique. Enjoy.

Read More

Using ASPX Like MVC

I love the organization of MVC when it comes to delivering content. Using a server-side controller you can see all the routing activity of your program. The controller can interact with the parent view as well as related partials, passing data and rendering html. Related views are also tucked-away together in the tree making it easy to pinpoint what you’re looking for. The default layout of WebForms is a different kind of animal. But using MVC experience as a reference you can structure your project to work in a similar way.

To begin we want to create a Views folder and inside that create a Home directory. The Home directory will contain the parent ASPX as well as any child ASPX pages for the dynamic content. When naming the child ASPX files be sure to prefix them with an underscore to follow MVC convention:

Tree Example

Next, we need to refine the Site.Master (or _Layout.cshtml in MVC). Make sure to add the script and style bundles to get jQuery and Twitter Bootstrap on the page. The ContentPlaceHolders (or sections in MVC) allow us to have placement control:
If any bundles are missing they can be added in App_Start/BundleConfig.cs.

In this example the parent ASPX contains a button that performs an ajax request. ContentPlaceHolders are used to inject code snippets in the proper location within Site.Master:
This is pretty straightforward. The script performs an ajax request to a partial ASPX. It passes data and retrieves HTML that is displayed to the user. The Index.cs file is not touched.

Next, we want to ensure the server can locate our parent page. A simple adjustment to the Web.config can accomplish that:
Now on to Models. You can also create Models to share between parents and partials. When creating a new Web Forms templated project it comes with a Models folder already. Inside is a model for account identity. Create a HomeModel.cs and place it in that folder. Next, add the following model to it which will be referenced later:
In any ASPX file you can add a using statement to reference our models:
Replace WebForms_Ajax with the name of your project. After that, all models can be shared between ASPX pages. This can reduce redundant coding.

The last step of the process is the partial. Under /Views/Home create an ASPX page named _Incomplete.aspx. The UI looks like:
Notice we have a full HTML document here. This is necessary to use the ASP.NET Web Server Controls. If you don’t include surrounding <html> tags then it won’t recognize tags prefixed with asp. But don’t worry, when we return the markup via ajax it won’t have any of that. We simply grab the contents of the <asp:PlaceHolder> tag.

Take note of the tags. This is what we use to add data to our page. They will repeat one to many times to add content to the page. Inside that repeater is another repeater whose data source is set automatically. The Eval() calls relate to the property names of our model.

The code behind does the magic. In Page_Load we fetch the data that was passed. It can be used to retrieve any additional information from a data source. Next, we construct our model to pass to the page. The model was declared in HomeModel.cs The RootRepeater is the name of the outermost repeater. We set the class equal to it’s data source. Notice we are placing the model in a list. A repeater requires a list or other IEnumerable object to work. Lastly, we grab the contents of the placeholder and return it with the response:
Download a DEMO.

Read More

Ajax to Retrieve HTML Segments from Single ASPX

Have you ever wanted to have one ASPX file that can render normal content as well as dynamic content? The dynamic content can return HTML that utilizes ASPX server controls. The segment returned is not cloned from hidden markup preexisting on the page, but rather is foreign and new as far as the DOM is concerned. If so then follow these steps to create one relay station for all your content:

In the aspx file we define a section that is reserved for our ajax request:
Of course this page also has other HTML and script that will render/bind on page load:
The script wires up the button. Here, we are using jQuery’s $.load function:
Alternatively, you can use $.ajaxto make the request. Note that I do not have a contentType or performing json encoding:
So onto the code behind. These alternations handle the initial load request as well as any subsequent ajax requests:
If you walk through it you can see we are routing everything through the HandleCallbacks method. We check for an ajax request. If one is not declared then we exit gracefully and everything is rendered in the ASPX apart from our placeholders. If it is an ajax request we retrieve our data, assign it to the repeater, make it’s placeholder visible, then render the segment using a writer. The transformed markup is returned as part of the Response and we load it into a location of our choosing.

Download a DEMO.

Next, we will cover how to make ajax requests to separate aspx files.


Read More

Ajax Script Loading that Enforces Order of Execution

One awesome feature of jQuery is the ability to load external scripts on demand. The $.getScript method loads the script behind the scenes via ajax. In fact the function is simply an alias to call to jQuery’s $.ajax function. By default that alias does not look for a cached items. In my particular need I wanted to observe a cache and guarantee order of execution. I resorted to using the $.ajax function directly since it offers more options. I did not want a script to load before it’s dependency nor did I want to bog down my page by doing synchronous requests. In no time at all I built my own mechanism to handle script requests.

My code basically loads one script at a time and waits until it is completely loaded before iterating to the next file. Once they are all loaded it will call the loadComplete function which can take advantage of those scripts. This method will load scripts as memory and resources are available, then perform the final action when complete. The user could be presented a loading gif or progress bar in the meantime.

Below I am showing an example using CDN scripts:

Read More

AJAX and Bootstrap Tabbing in MVC

In this tutorial you will see the Twitter Bootstrap tabstrip in action. I will be using MVC, Razor and jQuery to accomplish this. If you visit the tabstrip documentation you will see an example that uses static tab content. I have expanded upon that code snippet, converting it to dynamic content using AJAX. I’m also utilizing a fading transition effect as the content loads. The tabstrip will interact with two partial views named: _SearchTab.cshtml and _SubmissionTab.cshtml. Notice that I am naming the tab ids the same as the partial views. Doing that reduces translation in the script when relaying the AJAX calls.


The @Html.Partial will request the page on the active tab on page load. Place this call wherever the active class is being set.


The $.ajax() request retrieves the partial view. The cache parameter is necessary to ensure a fresh rebuild on each click. As for what path is requested you will notice a @ViewContext.RouteData.Values["controller"] call. It simply retrieves the controller of the current view, assuming the partial views are located in the same folder in the tree.


The above methods are needed to relay the $.ajax() request to the proper partial view.

Now each time you click on a tab it will load dynamic content from a partial view. Keeping content separate can keep code cleaner and more organized. Download an example implementing this technique.

Read More