jQueryMobile and ASP.NET Webforms

Posted by on

Leave a comment

With smart phone and tablet based web browsers controlling a significant share of the market it is becoming increasingly important for new and existing applications to accommodate these devices. Even with responsive designs that scale across different resolutions becoming more and more common there are often still consistency issues between different browsers on different devices. The goal of the jQuery Mobile library is to provide cross-browser support that allows developers to build applications that run across various mobile browsers and devices while providing the same (or at least very similar) user interface. Typically if you were to start an ASP.NET project utilising jQuery Mobile you would choose the ASP.NET MVC framework over traditional ASP.NET Web Forms and for good reason. The postback model employed in Web Forms interferes with the way jQuery Mobile handles form submissions automatically with Ajax. So any controls that cause a postback such as a LinkButton or a DropDownList are only going to create problems. Viewstate generated by ASP.NET controls can also become quite large on some pages which is exactly what you are trying to avoid on mobile sites. MVC has none of those limitations and gives you finer control of the rendered HTML so it makes more sense to utilise it. But what about situations where MVC is not an option? An older legacy website that is running on ASP.NET 2.0 for example? In this article I will share with you some workarounds that will help make your Web Forms/jQuery Mobile application possible.

Let’s get started

Let’s begin by creating a new ‘ASP.NET Empty Web Application’ and installing the jQuery Mobile package via Nuget. Our example will be a simple shopping cart with some pretty standard functionality such as the ability to add items to the cart, update the quantity of items, and remove items. To add these features create a models directory and add the following classes; Product, ShoppingCart, and ShoppingCartItem. The full source code for each class is available on GitHub. For simplicity sake we will store the current users shopping cart in a session property so get the source for the SessionHelper also. Now create a Master Page and insert the following HTML. It is based on the ‘Basic single page template’ available here but we have modified it to include some typical .NET elements like content placeholders.

Pay attention to the HTML in particular the different ‘data-‘ attributes. jQuery Mobile looks for HTML5 ‘data-‘ attributes and then injects mobile specific markup into those elements. Different ‘data-‘ attributes render to different things for example the div with the data-role=”header” attribute automatically becomes the header widget. For a list of all the data attributes refer to this page. Inside the <body> tag, each page on the site is identified with an element (usually a div) with the data-role=”page” attribute so we have added a ContentPlaceHolder for this. We also have a header that contains our navbar with the links to our future internal pages. Include this code in the Site.Master code behind to show the current cart status on every page:

Internal pages

Our default page will display a list of products.

We set the id of the page in the ‘page’ content region. Now we add a Repeater because it’s the most lightweight of the ASP.NET Web Forms list controls and we also have finer control of the markup it creates. We will use the Repeater to create an unordered list that has the data attribute data-role=”listview”. As you might have guessed when jQuery Mobile has finished rendering the page, this will become a listview widget. We will populate the list from some sample data (refer to GitHub for the full source code).

Our listview now contains products but how do we add them to the cart? In a traditional Web Form application you might add a LinkButton and that LinkButton would postback an sku to the server that you could use to add the item to the cart. But as I mentioned before that the postback model doesn’t play nicely with jQuery Mobile so we are going to use jQuery and an ASP.NET web service instead.

Json Web Services

Right click the project, then ‘add new item’, now add a new ‘WebService’ and call it CartFunctions.asmx. In order for our web service to be accessed from script it must be qualified with the ScriptServiceAttribute attribute. Be aware that if you are still running ASP.NET 2.0, the ScriptServiceAttribute is only available after installing the ASP.NET Ajax Extensions. Individual methods that are being called from script must be qualified with the WebMethodAttribute attribute and any of these methods that need access to the current session (where our cart is stored) must also have the EnableSession flag set to true. Here is what our ‘add to cart’ method looks like:

Back in our page we already have the following link:

In order to call our WebMethod from jQuery we need to attach an event to the link. Add a new JavaScript file, jquery.mobile-custom.js, and reference it in the Master Page. This is where we will add our jQuery events and other custom code. Usually when you add events to controls with jQuery you would do so in the document.ready hook eg

But jQuery Mobile now handles our page load events so you can’t rely on the regular hook. Instead we use jQuery Mobiles ‘pagecreate’ method, which fires when a page is loaded directly or via jQuery Mobiles Ajax navigation system. Here is how we can call our WebMethod:

Basically we are POSTing to our cartfunctions.asmx page and calling the AddToCart method. The content we send and receive is in json format. The sku we send to the method is obtained from a data attribute of the anchor tag. If the POST is successful we parse the Json we receive and call the setCartTotal method which updates the cart status on the Master Page.

Template trick

The last page we need to create is our shopping cart page where we update quantities, remove items, etc. The previous page simply called a web service that returned Json. Our shopping cart page however needs to submit a form that returns html as a result. We’ll be using the shopping cart logic in a number of places so the first thing I did was put it in to a user control that we can reuse. It’s a pretty simple control that gets the current content of the cart from the session and displays it. The cart page itself is also quite simple. It is just the cart control we created earlier but notice that it is wrapped in a form. Here is where it starts to get a little tricky. We are going to use another Web Form to generate the content for our shopping cart when it changes. Create the following web form, it’s really just a cut down version of the cart page, it’s the code behind that handles most of the magic. The code behind first looks for request parameters that determine if we are trying to remove an item or clear the cart all together. If the request parameters can’t be found then it looks for a form submission contains cart items (skus) and their quantities. Finally it updates our shopping cart control. In the javascript file the remove and remove all buttons post to our template like in the previous example. But this time the result is html and not json. We use the result like this:

This basically replaces the html of the cart with our new html that the Web Form created. Because it was added dynamically, it is important to call the jQuery Mobile ‘create’ method to ensure that all of the jQuery Mobile markup is applied. Handling the update cart is a little different, we need post our entire form this time. We can use a little trick to serialize the form and post it to our template with this code.

Serializing the form will combine the form values in to a string which can be sent to the server. Only successful controls that are valid for submission will be posted and the form elements must have a name attribute. A serialized form looks a little like this “first+name=Jarrod&last+name=Demeza”. ASP.NET Web Forms maintains control state between postbacks, it adds two extra input controls with ID __VIEWSTATE and __EVENTVALIDATION to the form. We have no use for these so we will exclude them using the ‘not()’ selector. Here is what our finished app should look like.

jQuery Mobile and ASP.NET Web Forms - Default

jQuery Mobile and ASP.NET Web Forms – Default

jQuery Mobile and ASP.NET Web Forms - Cart

jQuery Mobile and ASP.NET Web Forms – Cart

Like always the full source is available on Github.

Ajax issues

A few articles and answers on Stackoverflow have suggested disabling Ajax all together on jQuery Mobile in order to get things to work smoothly with Web Forms using the code below. Don’t do that unless you absolutely have to as it disables the built in page transitions/caching and other cool stuff that jQuery Mobile does in the first place. With the example I’ve provided and a little forethought you shouldn’t need to do this. The only thing you need to be aware of is to try not to use ids because the jQuery Mobile page container loads new pages in to its existing content, so the ids may not be unique. Use classes instead.

Share on FacebookShare on LinkedInTweet about this on TwitterShare on Google+Pin on PinterestEmail this to someone

Tags: , , , , , , ,

Related posts


No Comments Reply

Leave a Reply

© 2018 Meza Information Technology | Design by Vlad Carp

Back to top