Load Asp.net User Control dynamically using ajax enabled wcf

Many times we need to write user control. Why? Some reasons are UI decomposition for better managability, UI reuse for many pages etc. Now we need to load that user control. In static way we refer that controls in our markup and another dynamically load that controls using postback.

In ajax based web application hate postback. So we need to load that usercontrol without postback and when user wants. The problem is that there is no simple way you can do it.

However we can do one thing for solve the problem. In application's main page load time we can render all user control and then show and hide using javascript.

But in that solution some problem are there. If many user control is written then page will be very heavy and first load time will be very slow. User memory will be consumed more. Clients PC need to be powerful and may be others.

So we need to go ondemand load user control and when no need then remove it. But how?

I do it using Ajax enable wcf service. I wrote a method which is responsible for accept user control name and produce that user controls output html and sent to the client as json message format.

The service code like the following


[OperationContract]
[WebInvoke(RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json)]
public String GetUserControl(String controlName)
{
var page = new Page();
//usercontrol path
String controlPath = String.Concat(@"~\UC\" , controlName);
//load usercontrol in memory
UserControl control = (UserControl) page.LoadControl(controlPath);
//create html form
var form = new HtmlForm();
//add control to form
form.Controls.Add(control);
//add form to page
page.Controls.Add(form);

//create textwriter for accept html
var sw = new StringWriter();
HttpContext.Current.Server.Execute(page, sw, false);

//receive desired html
var data = sw.GetStringBuilder().ToString();
//return to the client
return data;
}


Now the client code. which is called the service. Here I use JQuery library for ajax communication. You may be use other library too.

function loadUserControl() {
jQuery.ajax({
url: "ControlLoader.svc/GetUserControl", //name of the service and service method
type: "POST",
data: '{"controlName":"SignUp.ascx"}', //parameter data as json string format
contentType: 'application/json; charset=utf-8',
success: function(data) { //success callback. where usercontrol html will be received
var obj = self.eval('(' + data + ')'); //create json object from string using eval functin. You may use other jsonconverters.
jQuery("#divSignUp").html(obj.d); //add this html to a specific div.
},
error: function(error) { //error
self.alert('Error for loading user control');
}
});
}

//Remove Loaded user control using javascript. No need to call any server side code.
function removeUserControl() {
jQuery("#divSignUp").html('');
}


Lastly you need to create a aspx page with 2 buttons and call those 2 javascript functions loadUserControl() and removeUserControl(). Then you can see the output.


Thanks for reading.

4 comments:

MyLifeAndCode said...

This is exactly what I was looking for, thanks! I was wondering if such a thing were possible -- returning a UserControl's HTML from a WCF call -- and it looks like, based on your example, you can. I'm going to follow your example and try to implement this. Thanks again!

aparna john said...

Hi,If your site takes like forever to load, then probably it is either composed of large file sizes in Web Design Cochin or your hosting account is not doing its task in delivering the web pages properly. Test your site first again and again before you officially launch it to the public.Thanks.....

Rohan Tikole said...

This dynamically generated controls are not accesible on post back. I have created a textbox using above method. Now by hitting submit button i want to read the value of this dynamic textbox. How to do?

Rohan Tikole said...

Please let me know