Recently I ran into a problem where I needed to reduce the size of a page, we had a page with a lot of drop down controls that may or my not be used. The problem with this was the size of the html was huge, every one of the controls was fully populated with over 50 items, next the view state was equally huge storing all of that content. The Solution, using WCF to load the control’s content on demand.
Starting off we need to get WCF configured, and this confused me, I had to manually register WCF in IIS, WHAT!! ok to save you the hassle of having to research how to do this, execute c:\WINDOWS\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\ServiceModelReg.exe –i and your good to go.
We have two options for populating the dropdowns, you can use a 3rd party control like Telerik’s radcombobox, or roll your own, which in some ways is fairly simple but rather involved, for right now I’m going to show you how to roll your own, to see how to use radComboBox see here.
Lets start with the WCF service, create a Ajax enabled WCF service. For what ever reason I had to remove the namespace to get this to work, and the examples I found online had it removed as well, this is something I’m going to research more on later. Next we need to build a data entity to hold the data, nothing fancy just something like thisnext we build the service, in this case I’m just building some data. when you add the Ajax enabled WCF service some items will be added to the system.serviceModel section of the web config in this case it looks like this if your not able to get your service to work with the Namespace, and you remove it, make sure to also remove it from the contract attribute in the endpoint node of the service node.
The onFailure is called when the service call fails, and for this we are just doing a simple alert to say it failed.
The next part is getting the data out when the page is submitted, because we are not using any view state we can’t get the value the same way we would with a regular asp.net control, we have to pull it from Request.Form collection. Finally we need to add a way to set an option as selected. The code to set the selected option is already there we just have to utilize it by setting the value of var selectedOptionValue, to do this we use the ClientScript.RegisterStartupScript like this
This sets the control to be updated, set the selected value, then populates the the control from the webservice.
Like I said it’s kind of a long process but you can cut down your page size a lot if your doing multiple dropdowns with large amounts of data that may not be used.
As always the full source code for this project is available (here).