aspx Tutorial

.NET Articles,jQuery demo, asp.net with jQuery, online tutorial,Jquery, SilverLight, Javascript, asp.net,JSON, MVC,.NET Articles,demo, Web Services, .NET articles, Sharepoint 2010, visual studio 2010,Aamir Hasan,IT, Building Your First Web Application Project
Advertise Here

Toolbar

Get our toolbar!

Advertize



Posted by Aamir Hasan   on Sunday, January 2, 2011 Total Views:  

In this example, I have created a web user control called WebUserControl.ascx that had a gridview with some records. In the Default.aspx, I have used Ajax.Method to send a web user control name to a  web service and web service have rendered instance of WebUserControl.ascx when button is clicked.
The purpose of an example have to demonstrate  that how to load web user control dynamically using jQuery.Let’ s start.

Step 1: Open Visual Studio 2010. Create new ASP.NET 4.O Web site from File -> New -> Web Site.

Step 2: Right click the web site -> Add New Item -> Web User Control. Click Add button to create WebUserControl.ascx.


Step 3: Drag & Drop a gridview in the WebUserControl.ascx. I have created a Fruit class which will return the Fruit List and bind to gridview, WebUserControl.ascx.cs page code is given below.

C#

public partial class WebUserControl : System.Web.UI.UserControl
{
   protected void Page_Load(object sender, EventArgs e)
   {
       GridView1.DataSource = getFruitList();
       GridView1.DataBind();
   }
   public List<Fruit> getFruitList()
   {
       List<Fruit> Obj = new List<Fruit>(){
           new Fruit{ Name="Apple",  Price=20, Qantity=100},
           new Fruit{ Name="Banana",  Price=25, Qantity=1500},
           new Fruit{ Name="Manago",  Price=40, Qantity=400},
           new Fruit{ Name="Orange",  Price=60, Qantity=300},
       };
       return Obj;
   }
   public class Fruit
   {
       public string Name { get; set; }
       public int Qantity { get; set; }
       public double? Price { get; set; }
   }
}

VB.NET

Partial Class WebUserControl
   Inherits System.Web.UI.UserControl
   Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
       GridView1.DataSource = getFruitList()
       GridView1.DataBind()
   End Sub

   Public Function getFruitList() As List(Of Fruit)
    Dim Obj As New List(Of Fruit)() With { _
        New Fruit() With { _
            .Name = "Apple", _
            .Price = 20, _
            .Qantity = 100 _
        }, _
        New Fruit() With { _
            .Name = "Banana", _
            .Price = 25, _
            .Qantity = 1500 _
        }, _
        New Fruit() With { _
            .Name = "Manago", _
            .Price = 40, _
            .Qantity = 400 _
        }, _
        New Fruit() With { _
            .Name = "Orange", _
            .Price = 60, _
            .Qantity = 300 _
        } _
    }
       Return Obj
   End Function
   Public Class Fruit
       Public Property Name() As String
           Get
               Return m_Name
           End Get
           Set(ByVal value As String)
               m_Name = value
           End Set
       End Property
       Private m_Name As String
       Public Property Qantity() As Integer
           Get
               Return m_Qantity
           End Get
           Set(ByVal value As Integer)
               m_Qantity = value
           End Set
       End Property
       Private m_Qantity As Integer
       Public Property Price() As System.Nullable(Of Double)
           Get
               Return m_Price
           End Get
           Set(ByVal value As System.Nullable(Of Double))
               m_Price = value
           End Set
       End Property
       Private m_Price As System.Nullable(Of Double)
   End Class
End Class

Step 4: Open your Default.aspx.cs/vb page and create a static function which will accepts the control name and pass to another static function to load the control and render it and return a string  to the jQuery function from the server-side to client-side.

C#

   [WebMethod]
   public static string Result(string controlName)
   {
       return RenderControl(controlName);
   }

   public static string RenderControl(string controlName)
   {
       Page page = new Page();
       UserControl userControl = (UserControl)page.LoadControl(controlName);
       userControl.EnableViewState = false;
       HtmlForm form = new HtmlForm();
       form.Controls.Add(userControl);
       page.Controls.Add(form);

       StringWriter textWriter = new StringWriter();
       HttpContext.Current.Server.Execute(page, textWriter, false);
       return textWriter.ToString();
   }

VB.NET

   <WebMethod()> _
   Public Shared Function Result(ByVal controlName As String) As String
       Return RenderControl(controlName)
   End Function

   Public Shared Function RenderControl(ByVal controlName As String) As String

       Dim page As New Page()
       Dim userControl As UserControl = DirectCast(page.LoadControl(controlName), UserControl)
       userControl.EnableViewState = False
       Dim form As New HtmlForm()
       form.Controls.Add(userControl)
       page.Controls.Add(form)

       Dim textWriter As New StringWriter()
       HttpContext.Current.Server.Execute(page, textWriter, False)
       Return textWriter.ToString()
   End Function

Note: Add following references in the code behind of WebUserControls.ascx.cs/ascx.vb to enable StringWriter class & Web Method.

C#

using System.Web.Services;
using System.IO;

VB.NET

Imports System.IO
Imports System.Web.Services


Step 5: Now open your Default.aspx Page and add the jQuery as shown below:

   <script src="http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript"></script>
   <script type="text/javascript" src="http://github.com/malsup/blockui/raw/master/jquery.blockUI.js?v2.34"></script>
   <script type="text/javascript">
       $(document).ready(function () {
           $('#Button1').click(function () {
               $.blockUI({ message: '<h1> Processing...</h1>' });
               var ControlName = "WebUserControl.ascx";
               $.ajax({
                   type: "POST",
                   url: "Default.aspx/Result",
                   data: "{controlName:'" + ControlName + "'}",
                   contentType: "application/json; charset=utf-8",
                   dataType: "json",
                   success: function (response) {
                       $.unblockUI();
                       $('#result').html(response.d);
                   },
                   failure: function (msg) {
                       $.unblockUI();
                       $('#result').html(msg);
                   }
               });
           });
       });      
   </script>

Step 7: Add following code under the body content of Default.aspx page.

   <p>
       <input type="button" id="Button1" value="Load Control" />
       <div id="result">&nbsp;</div>
   </p>

When the button is clicked the Ajax.Method fetch the string converted data and load into div element as shown below.

Here’s a preview of the collection List bind to gridview when web user control is loaded.

Here’s a preview of the string return to Ajax.Method from server side to client side.

Output

Download

Load Control.zip (4.65 kb)

Protected by Copyscape Online Plagiarism Tool

Comments (26) -

Search Engine Optimization Top Ranking
Search Engine Optimization Top Ranking Australia
8/23/2012 2:02:24 AM #

Toprankseo.com.au, <a href="http://www.toprankseo.com.au/">search engine</a> optimisation company uses well tested methods to bring your websites in top ranking in very affordable price. In Sydney we are among the best companies who work with highly experienced and qualified employees.

Search Engine Optimization Top Ranking
Search Engine Optimization Top Ranking Australia
8/23/2012 2:02:31 AM #

Toprankseo.com.au, <a href="http://www.toprankseo.com.au/">search engine</a> optimisation company uses well tested methods to bring your websites in top ranking in very affordable price. In Sydney we are among the best companies who work with highly experienced and qualified employees.

jvp service centre
jvp service centre Australia
9/26/2012 2:34:40 AM #

Jvp service centre is a center to repair all electronic items. It is a service and repair center which repairs all types of brand TV, camera, microwave and many more items. We also offer extended warranty in repaired products and their parts. more info visit http://www.jvpservicecentre.com.au/services/

jvp service centre
jvp service centre Australia
9/26/2012 2:34:52 AM #

Jvp service centre is a center to repair all electronic items. It is a service and repair center which repairs all types of brand TV, camera, microwave and many more items. We also offer extended warranty in repaired products and their parts. more info visit http://www.jvpservicecentre.com.au/services/

jvp service centre
jvp service centre Australia
9/26/2012 2:35:10 AM #

Jvp service centre is a center to repair all electronic items. It is a service and repair center which repairs all types of brand TV, camera, microwave and many more items. We also offer extended warranty in repaired products and their parts. more info visit http://www.jvpservicecentre.com.au/services/

The Best Mobile Phone Deals - www.contract-mobile-phone-deal.co.uk
The Best Mobile Phone Deals - www.contract-mobile-phone-deal.co.uk United Kingdom
10/3/2012 1:29:34 AM #

Lowest cost official contract mobile phone deals UK. Free gifts & offers on Nokia, Samsung, Sony Ericsson, Blackberry, HTC, LG, Apple & Motorola smart-phones range.

Seo Link Building Service - www.technologus.com
Seo Link Building Service - www.technologus.com India
10/24/2012 7:20:27 PM #

One Way & Reciprocal SEO Expert Link Building Services providing Company to increase your presences on search engines. Link popularity Agency for UK, USA & Australia to Increase business & online search results.

sydney wide escort models
sydney wide escort models United States
10/31/2012 8:11:58 AM #

Outstanding! It is great in order to find a good post on this topic.
http://www.sydneywideescorts.com.au/swe/

as
as People's Republic of China
11/11/2012 9:15:11 PM #

[url=perfectlvreplica.com/...r-Azur-Canvas-cid-471.html] louis vuitton Damier Azur Canvas[/url]
[url=perfectlvreplica.com/...-Ebene-Canvas-cid-472.html]louis vuitton Damier Ebene Canvas[/url]
[url=perfectlvreplica.com/Monogram-Canvas-cid-482.html] louis vuitton Monogram Canvas[/url]
[url=perfectlvreplica.com/Monogram-Denim-cid-483.html]louis vuitton Monogram Denim[/url]
[url=perfectlvreplica.com/Monogram-Idylle-cid-485.html]louis vuitton Monogram Idylle[/url]
[url=perfectlvreplica.com/...m-Multicolore-cid-487.html]louis vuitton Monogram Multicolore[/url]
[url=perfectlvreplica.com/...ram-Empreinte-cid-522.html]louis vuitton Monogram Empreinte[/url]
[url=perfectlvreplica.com/Monogram-Vernis-cid-489.html]louis vuitton Monogram Vernis[/url]
[url=http://perfectlvreplica.com/Sobe-cid-492.html]louis vuitton Sobe[/url]
[url=perfectlvreplica.com/Taiga-Leather-cid-497.html]louis vuitton Taiga Leather[/url]

consolidatedselfstorage
consolidatedselfstorage United Kingdom
12/2/2012 10:09:07 PM #

Hello viewers here is something to telling about <a href=" www.consolidatedselfstorage.co.uk/for.asp; consolidatedselfstorage co uk - removals and storage London</a> We are Looking for storage space in or around London, there  companies that you can hire if you are looking and Self storage is the best in UK , self storage London , storage London , safe storage London , removals and storage London .

consolidatedselfstorage
consolidatedselfstorage United Kingdom
12/2/2012 10:09:20 PM #

Hello viewers here is something to telling about <a href=" www.consolidatedselfstorage.co.uk/for.asp; consolidatedselfstorage co uk - removals and storage London</a> We are Looking for storage space in or around London, there  companies that you can hire if you are looking and Self storage is the best in UK , self storage London , storage London , safe storage London , removals and storage London .

afro disiacuk
afro disiacuk United Kingdom
12/16/2012 7:16:50 PM #

Hello viewers here is something to telling about <a href=" http://www.afro-disiac.co.uk/">; Best listen to music online</a> Online largest free music community. DJs can upload and share our party .and other audio  We are Looking for download mix music  tracks to produce mashups, soundtracks and virtual DJ and much more programs , Spotify works on your computer, your mobile, your tablet, and your home entertainment system.

afro disiacuk
afro disiacuk United Kingdom
12/16/2012 7:17:41 PM #

Hello viewers here is something to telling about <a href=" http://www.afro-disiac.co.uk/">; Best listen to music online</a> Online largest free music community. DJs can upload and share our party .and other audio  We are Looking for download mix music  tracks to produce mashups, soundtracks and virtual DJ and much more programs , Spotify works on your computer, your mobile, your tablet, and your home entertainment system.

afro disiacuk
afro disiacuk United Kingdom
12/16/2012 7:18:10 PM #

Hello viewers here is something to telling about  http://www.afro-disiac.co.uk/

pgs golf
pgs golf United Kingdom
1/2/2013 12:08:10 AM #

Hello viewers here is something to telling about <a href=" http://pgsgolf.co.uk/shop/flags/">; Golf Flag</a> Poles Manufacturers & Flag Poles Suppliers. promotional team sport club Manufacturer and Flag provides high quality flags and flagpoles at extremely sports clubs in UK , We also supply our products to golf .

pgs golf
pgs golf United Kingdom
1/2/2013 12:08:44 AM #

Hello viewers here is something to telling about <a href=" http://pgsgolf.co.uk/shop/flags/">; Golf Flag</a> Poles Manufacturers & Flag Poles Suppliers. promotional team sport club Manufacturer and Flag provides high quality flags and flagpoles at extremely sports clubs in UK , We also supply our products to golf .

pgs golf
pgs golf United Kingdom
1/2/2013 12:09:17 AM #

Hello viewers here is something to telling about http://pgsgolf.co.uk/s

pgs golf
pgs golf United Kingdom
1/2/2013 12:09:27 AM #

Hello viewers here is something to telling about - pgsgolf.co.uk/s

pgs golf
pgs golf United Kingdom
1/2/2013 12:09:33 AM #

Hello viewers here is something to telling about - pgsgolf.co.uk/

pgs golf
pgs golf United Kingdom
1/2/2013 12:09:42 AM #

pgsgolf.co.uk/

pgs golf
pgs golf United Kingdom
1/2/2013 12:09:56 AM #

Hello viewers here is something to telling about <a href=" http://pgsgolf.co.uk/shop/flags/">; Golf Flag</a> Poles Manufacturers & Flag Poles Suppliers. promotional team sport club Manufacturer and Flag provides high quality flags and flagpoles at extremely sports clubs in UK , We also supply our products to golf .

pgs golf
pgs golf United Kingdom
1/2/2013 12:10:00 AM #

Hello viewers here is something to telling about <a href=" http://pgsgolf.co.uk/shop/flags/">; Golf Flag</a> Poles Manufacturers & Flag Poles Suppliers. promotional team sport club Manufacturer and Flag provides high quality flags and flagpoles at extremely sports clubs in UK , We also supply our products to golf .

Db
Db India
2/7/2013 4:43:21 PM #

Good work!!
But if the page is in master page ,this code is no work.
it error gives "405 method not allowed"

LDF2-50
LDF2-50 United States
5/7/2013 12:25:59 AM #

Hello I wish to to share a comment here concerning you to definitely be able to inform you just how much i personally Loved this particular study. I have to elope in order to aTurkey Day time Supper but desired to leave ya an easy comment. We preserved you Same goes with be returning subsequent function to read more of yer quality articles. Keep up the quality work.

antennasystems.com/category/cable-andrew.html

tools
tools United States
6/3/2013 4:50:37 AM #

Hello I wish to to share a comment here concerning surveillance.jono1.com/.../#comment-238youhttp://antennasystems.com/category/cable-andrew.html
to definitely be able to inform you just how much i personally Loved this particular study. I have to elope in order to aTurkey Day time Supper but desired to leave ya an easy comment. We preserved you Same goes with be returning subsequent function to read more of yer quality articles. Keep up the quality work.

http://antennasystems.com/category/Services.html

Minda Blanko
Minda Blanko United States
9/20/2013 9:13:38 AM #

Hello, I enjoy reading all of your article. I wanted to write a little comment to support you.|

hostgator review
hostgator review United States
11/2/2013 5:01:29 AM #

I WILL LIKE 2 BUY MANY IPHONES BUT THE ONLY THING I WILL SAY THAT IF U BUY LIKE 20 OF THE THEM DO U GET A CHEAP PRICE THEN HOW MUCH WILL IT COME UP 2 IPHONE 4 S

Reginald
Reginald United States
3/28/2014 6:45:00 PM #

Hi! Superb blog post you had written above. Professionally, you have explained all the necessary pointers and I have even jot them down for future usage. Keep writing and thank you for writing the stunning info.

Reginald C
Reginald C United States
4/1/2014 12:34:24 AM #

Good afternoon. Good write up you had written there. Personally, you have nailed everything and I have even jot them down for future reading. Keep up the fantastic work and I appreciate you for discussing the useful info!

Slyvia Wellborn
Slyvia Wellborn United States
5/30/2014 12:13:33 AM #

of course like your web-site however you have to check the spelling on several of your posts. Several of them are rife with spelling issues and I to find it very bothersome to tell the reality nevertheless I will definitely come back again.

Detra Honerkamp
Detra Honerkamp United States
6/3/2014 2:05:41 AM #

You should take part in a contest for one of the best blogs on the web. I will recommend this site! More For xxx video http://www.uxxx.me/

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

Advertizement 1
Advertizement 2
Advertizement 3
Advertizement 4
Advertizement 5