In one of the projects I have developed on client side(jquery,Html),I used this approach of loading the user control without getting any page postback.
If you are naïve to jquery ajax calling code behind method then you have to go through my previous blog 'http://blogs.effectlabs.com/post/2012/02/24/jquery-ajax-calling-Wcf-service-or-some-method-in-Code-behind-from-Client-Side.aspx.
Now here I am adding two user controls one by one on my aspx page(Default.aspx) depending on which button is clicked.
The same javascript method which I have used in previous blog to call code behind method is used i.e
function ClientProxyDateFormatted(methodName, paramArray, successFunction, errorFunction) {
var pagePath = window.location.pathname;
var paramList = '';
if (paramArray.length > 0) {
for (var i = 0; i < paramArray.length; i += 2) {
if (paramList.length > 0) paramList += ',';
paramList += '"' + paramArray[i] + '"' + ':' + '"' + paramArray[i + 1] + '"';
}
}
paramList = '{' + paramList + '}';
var length = pagePath.length;
if (pagePath.substring(length - 1, length) == "/") {
pagePath += "Default.aspx";
}
else if (pagePath.substring(length - 5, length) != ".aspx") {
pagePath += "/Default.aspx";
}
$.ajax({
type: "POST",
url: pagePath + "/" + methodName,
contentType: "application/json; charset=utf-8",
data: paramList,
dataType: "text",
processData: false,
success: function (msgg) {
var msg = JSON.parse(msgg, function (key, value) {
var a;
if (value != null) {
if (value.toString().indexOf('Date') >= 0) {
a = /^\/Date\((-?[0-9]+)\)\/$/.exec(value);
if (a) {
var dt = new Date(parseInt(a[1], 10));
return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
}
}
return value;
}
});
successFunction(msg);
},
error: function (xhr, status, error) {
errorFunction(xhr, status, error);
}
});
return false;
}
Now add this method or reference to the javascript file(common.js in my case) in which this method is present on your aspx page.I have used two user controls namely MyUserControl1.ascx and MyUserControl2.ascx which are added on main page on button ‘btnLoadControl1’ and button ‘btnLoadControl2’ clicks respectively. After this write the code below on your aspx page under script tag.
<script type="text/javascript"> var globalUserControlList= new Array();
$(document).ready(function () {
$('#btnLoadControl1').click(function () {
var userControl = this.id;
$('#wrap>div').hide();
if ($.inArray(userControl, globalUserControlList) >= 0) {
$('#ucFirst').show();
}
else {
globalUserControlList.push(userControl);
LoadViewMyProfileUc(userControl);
}
});
$('#btnLoadControl2').click(function () {
var userControl = this.id;
$('#wrap>div').hide();
if ($.inArray(userControl, globalUserControlList) >= 0) {
$('#ucSecond').show();
}
else {
globalUserControlList.push(userControl);
LoadViewMyProfileUc(userControl);
}
});
});
function LoadViewMyProfileUc(userControl) {
ClientProxyDateFormatted("LoadUserControl", ['controlId', userControl],
function (msg) { succesfulLoadUserControl(msg); }, function (xhr, status, error)
{ errorLoadUserControl(xhr, status, error); });
}
function succesfulLoadUserControl(msg) {
$('#wrap').append(msg.d);
}
function errorLoadUserControl(xhr, status, error) {
alert('Error Loading UserControl')
}
</script>
Here Array globalUserControlList keeps the track of user controls already loaded.If they are already present on aspx page ,it does not reload them,but just show them by using jquery method (.show()) otherwise it calls the method LoadViewMyProfileUc(userControl) which contains one parameter i.e clicked button’s id which tells us the user control to be loaded.LoadUserControl is the method in code behind which decides which user control to load.
Add Code below to some div on your aspx page
<div id='mainDiv'>
<div id='buttonDiv'>
<a id='btnLoadControl1'>Load First</a>
<a id='btnLoadControl2'>Load Second</a>
</div>
<div id='wrap'>
</div>
</div>
Below is the Code in .cs file
[WebMethod]
public static string LoadUserControl(string controlId)
{
switch (controlId)
{
case "btnLoadControl1":
return RenderControl("~/UserControls/MyUserControl1.ascx");
case "btnLoadControl2":
return RenderControl("~/UserControls/MyUserControl2.ascx");
}
return null;
}
public static string RenderControl(string controlName)
{
var page = new Page();
var userControl = (System.Web.UI.UserControl)page.LoadControl(controlName);
userControl.EnableViewState = false;
page.Controls.Add(userControl);
var textWriter = new StringWriter();
HttpContext.Current.Server.Execute(page, textWriter, false);
return textWriter.ToString();
}
We are using the string writer class in method RenderControl to read the html of user control and return this html to Successful Function of the client side method on aspx page.The html is contained in msg.d of method succesfulLoadUserControl(msg) which we append to our container div (wrap).
Below are the snap shots of successful loading of User Controls
![snap2_thumb[8] snap2_thumb[8]](http://blogs.effectlabs.com/image.axd?picture=snap2_thumb%5B8%5D_thumb.png)
I have attached a sample project below
LoadingUserControl.zip (265.93 kb)