Subscribe: Dot Net World : Your Source For Dot Net Tips and Tricks
Added By: mdubey1987 Feedage Grade B rated
code  data  function  jquery  model  net  new  page  public  result  script  server  set  sql server  string  student 
Rate this Feed
Rate this feedRate this feedRate this feedRate this feedRate this feed
Rate this feed 1 starRate this feed 2 starRate this feed 3 starRate this feed 4 starRate this feed 5 star

Comments (0)

Feed Details and Statistics Feed Statistics
Preview: Dot Net World : Your Source For Dot Net Tips and Tricks

Dot Net World

C# | ASP.Net | MVC | SQL Server | jQuery | Java Script

Updated: 2017-07-28T11:50:49.252+05:30


ASP.Net MVC - Multiple Models in Single View - Part2


In last post, we have talked about different approaches to pass the multiple models in single view. We have also looked some of them like Dynamic,View Data and View Bag.This post is the continuation of previous post. Here we will see the use of ViewModel,Tuple and ViewComponent for passing multiple model in single view . Let's first see what was our problem statement-Problem StatementWe have two models Student and Course and we need to show the the list of Students and Courses in a single view.Below are the model definition for Student and Coursepublic class Student{ public int StudentID { get; set; } public string StudentName { get; set; } }public class Course{ public int CourseID { get; set; } public string CourseName { get; set; }}Solutions to achieveHere we will see ViewModel,Tuple and ViewComponent to achieve our requirement1. View ModelViewModel is a class which contains the properties which are represented in view or represents the data that we want to display on our view.If we want to create a View where we want to display list of Students and Courses then we will create our View Model (StudentCourseViewModel.cs).ViewModel Classpublic class StudentCourseViewModel{ public List allCourses { get; set; } public List allStudents { get; set; }}Action Methodpublic IActionResult UsingViewModel(){ ViewBag.Message = "Passing Multiple Model using ViewModel"; StudentCourseViewModel vm = new StudentCourseViewModel(); vm.allStudents = Repository.GetStudents(); vm.allCourses = Repository.GetCourses(); return View(vm);}View Code@using MVCCustomModelBinding.Models.ViewModels@model StudentCourseViewModel@{ ViewBag.Title = "Home Page";}


Student List

@foreach (var item in Model.allStudents) { }
Student IDStudent Name

Course List

@foreach (var item in Model.allCourses) { }
Course IDCourse Name
2. TupleA Tuple object is an immutable, fixed-size and ordered sequence object. Each object in tuple is being of a specific type.The .NET framework supports tuples up to seven elements.Using this tuple object we can pass multiple models from the controller to the view.Action Methodpublic IActionResult UsingTuple(){ ViewBag.Message = "Passing Multiple Model using Tuple"; var tupleModel = new Tuple, List>(Repository.GetStudents(), Repository.GetCourses()); return View(tupleModel);}View Code@using MVCCustomModelBinding.Models@model Tuple,List>@{ ViewBag.Title = "Home Page";}


Student List

@foreach (var item in Model.Item1) { [...]

ASP.Net MVC - Multiple Models in Single View - Part1


In MVC we cannot use multiple model tag on a view. But Many times we need to pass multiple models from controller to view or we want to show data from multiple model on a view. So In this post we will see the different ways to bind or pass the multiple models to single view.Problem StatementLets suppose we have two models Student and Course and we need to show the the list of Students and Courses in a single view.Below are the model definition for Student and Coursepublic class Student{ public int StudentID { get; set; } public string StudentName { get; set; } }public class Course{ public int CourseID { get; set; } public string CourseName { get; set; }}Below is the Repository class which have two method for returning the list of Students and Coursespublic class Repository{ public static List GetStudents() { return new List{ new Student() { StudentID = 1, StudentName = "Manish" }, new Student() { StudentID = 2, StudentName = "Prashant" }, new Student() { StudentID = 3, StudentName = "Deepak" } }; } public static List GetCourses() { return new List { new Course () { CourseID = 1, CourseName = "Chemistry"}, new Course () { CourseID = 2, CourseName = "Physics"}, new Course () { CourseID = 3, CourseName = "Math" }, new Course () { CourseID = 4, CourseName = "Computer Science" } }; }}OutputOutput of all approaches will be similar to the screenshot shown below:Solutions to achieveThere are many ways of using multiple models in a view, most frequently used are given below:DynamicViewDataViewBagViewModelTupleViewComponent(ASP.NET Core MVC feature)Let's see all the approaches one by one with example-1. DynamicThe ExpandoObject class enables us to add and delete members at run time.So If we want to build up an object to work with on the fly at runtime then we can use Expando Object.Let's see how can we use ExpandoObject with Multiple Models.Action Methodpublic IActionResult UsingDynamic() { ViewBag.Message = "Passing Multiple Model using dynamic Model"; dynamic mymodel = new System.Dynamic.ExpandoObject(); mymodel.Students = Repository.GetStudents(); mymodel.Courses = Repository.GetCourses(); return View(mymodel);}In our View, we can define our model as dynamic (not a strongly typed model) using the @model dynamic keyword.View Code@using MVCCustomModelBinding@model dynamic@{ ViewBag.Title = "Home Page";}


Student List

Student IDStudent Name
@foreach (var item in Model.Students) { }
Student IDStudent Name

Course List

@foreach (var item in Model.Courses) { }
Course IDCourse Name
2. View DataViewData is used to transfer data from the controller to the view. ViewData is a dictionary object that may be accessible using a string as the key. Using ViewData, we can pass any object from the controller [...]

Deserialize XML to C# object


In this post we will see the simple approach to deserialize XML to C# object.

Our XML String

string xmlString = "1Manish Dubey2Pankaj";

Create our class

public class Student
public int Id { get; set; }
public string Name { get; set; }

Create XML Serializer and StringReader Object

//First argument is type of object and second argument is root attribute of your XML string/source

XmlSerializer serializer = new XmlSerializer(typeof(List), new XmlRootAttribute("Students"));
StringReader stringReader = new StringReader(xmlString);;

At last, deserialize XMl to C# object

List studentList = (List)serializer.Deserialize(stringReader);


Add caption


ASP.Net MVC - Custom Model Binding


In last article, we have discussed about what is ASP.NET Model binding and saw a basic introduction to the Model Binder. In this post we will see creating Custom Model Binding in ASP.Net MVC with simple example.Model Binder in ASP.NET MVCFor model binding MVC uses the following types-IModelBinder interface - This defines methods that are required for a Model Binder, like the BindModelAsync method. This method is responsible for binding a model to some values using ModelBindingContextIModelBinderProvider interface - This interface contains methods that enables dynamic implementation of model binding for classes which implement the IModelBinder interface. This is used to manage the custom binder for the type of data posted by the end-user in views.Creating Custom Model BinderWe creating our custom model binder by implementing the IModelBinder and IModelBinderProvider interfaces. Let see how we will do that. Note :I have used ASP.Net MVC Core project here.All the codes are in ASP.Net MVC Core.View PageWe have below form for adding new Student. There are three fields Student ID, First Name and Last Name(to keep it simple).ModelIn my model, I will only have one property StudentName for saving Student Name.namespace MVCCustomModelBinding.Models{ public class Student { public int StudentID { get; set; } public string StudentName { get; set; } }}Action MethodIn controller, we have below action method for adding new student record.[HttpPost] /// /// Action Method for adding new student record /// /// public IActionResult Create(Student student) { /*Code for saving student in database*/ return View("Index"); }Custom BindingAs you can see above, we have two fields Fisrt Name and Last Name in our Student form while in our action method we have passed Student model object as parameter which have only one property StudentName. Here we are going to create our custom model binder to capture the current request and extract the Form fields individually. Then we will manipulate Fisrt Name and Last Name fields any way we like. In this example as you can see I am adding them to a single property called StudentName. Below is the code-using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc.ModelBinding;using MVCCustomModelBinding.Models;using System;using System.Threading.Tasks;namespace MVCCustomModelBinding.CustomBinder{ /// /// Custom Model Binder /// public class StudentCustomBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) throw new ArgumentNullException(nameof(bindingContext)); HttpRequest request = bindingContext.HttpContext.Request; string stdName = request.Form["StudentFirstName"] + " " + request.Form["StudentLastName"]; string stdId = request.Form["StudentID"]; bindingContext.Result = ModelBindingResult.Success(new Student { StudentID = int.Parse(stdId), StudentName = stdName }); return Task.CompletedTask; } } /// /// Custom Model Binder Provider /// public class StudentCustomBinderProvider : IModelBinderProvider { public IModelBinder GetBinder(ModelBinderProviderContext context) { //Return null if model type is not Student if (context.Metadata.ModelType != typeof(Student)) { return null; } return new StudentCustomBinder(); } }}Register Custom BinderWe will add the above custom model provider class in the application, so that application will load it in the model binder process. Open Startup.cs and add the following line ConfigureServices method.// This method gets called by the runtime. Use this method to add services to the container.public void ConfigureServices(IServiceCollection services){ // Add framework services. services.AddApplicationInsi[...]

ASP.Net MVC Model Binding


Model BindingWhat is Model Binding?Model Binding in ASP.Net MVC maps the data from HTTP request to action method parameters. These parameters may be simple types such as string, integer or they may be complex type. It is a great feature as it relieves developer from writing all the type casting and “HTML-Model mapping code”. The Model binder is capable of retrieving the data from HTML form variables, POSTed variables and files, query string parameters and the values added in the routes.How model binding works?When MVC receives HTTP request, it routes the request to a specific action method of a controller. It determines which action method is going to execute based on what is in the route data, then it maps values from the HTTP request to action method’s parameter(s). For ex. Consider the below URL- the route template is looks like {controller}/{action}/{id?}, books/edit/2 routes to the Books controller and its Edit action method. It also accepts an optional parameter id. Action method code should look something like this-public IActionResult Edit(int? id)MVC will try to bind request data to the action parameters by name and use the DefaultModelBinder class which magically does all the type conversion and mapping of all value(s). MVC model binding binds the data from various parts of request and it does so in set of order. Below is a list of the data sources in the order that model binding looks through them:Form values: These are form values that go in the HTTP request using the POST method. (including jQuery POST requests).Route value: The set of route values provided by Routing.Query strings: The query string part of the URL. Since model binding asked for a key named id and there is nothing named id in the form values, it moved on to the route values looking for that key. In our example, it's a match. Binding happens, and the value is converted to the integer 2. The same request using Edit(string id) would convert to the string"2".When a parameter is bound, model binding stops looking for values with that name and it moves on to bind the next parameter. If binding fails, MVC does not throw an error. You can query for model state errors by checking the ModelState.IsValid property.Model Binding AttributesMVC contains several attributes that you can use to direct its default model binding behavior to a different source. For example, you can specify whether binding is required for a property, or if it should never happen at all by using the [BindRequired] or [BindNever] attributes. Alternatively, you can override the default data source, and specify the model binder's data source. Below is a list of model binding attributes:[BindRequired]: This attribute adds a model state error if binding cannot occur.[BindNever]: Tells the model binder to never bind to this parameter.[FromHeader], [FromQuery], [FromRoute], [FromForm]: Use these to specify the exact binding source you want to apply.[FromServices]: This attribute uses dependency injection to bind parameters from services.[FromBody]: Use the configured formatters to bind data from the request body. The formatter is selected based on content type of the request.[ModelBinder]: Used to override the default model binder, binding source and name.Attributes are very helpful tools when you need to override the default behavior of model binding.In this article, we have only discussed about what is ASP.NET Model binding and saw a basic introduction to the Model Binder. The model binding process can be customized by implementing the custom model binder and value providers.[...]

ASP.NET 4.5 Architecture


Request Processing 

  1. IIS gets the request
  2. Looks up a script map extension and maps to aspnet_isapi.dll
  3. Code hits the worker process (aspnet_wp.exe in IIS5 or w3wp.exe in IIS6)
  4. .NET runtime is loaded
  5. IsapiRuntime.ProcessRequest() called by non-managed code
  6. IsapiWorkerRequest created once per request
  7. HttpRuntime.ProcessRequest() called with Worker Request
  8. HttpContext Object created by passing Worker Request as input
  9. HttpApplication.GetApplicationInstance() called with Context to retrieve instance from pool
  10. HttpApplication.Init() called to start pipeline event sequence and hook up modules and handlers
  11. HttpApplicaton.ProcessRequest called to start processing
  12. Pipeline events fire
  13. Handlers are called and ProcessRequest method is fired
  14. Control returns to pipeline and post request events fire

SQL : Sql Query Execution Order


Most programming languages executes set of statements from Top to Bottom but SQL Server executes set of statements in a logical order which is uniquely decides by the SQL Server in a predefined order known as Logical Query processing phase.


When we are developing an application our concern mostly related to the code optimization which enhances the performance of application. When we are talking about an application it has broadly divided into two part one is the our code written in any programming language and other is the code written in database which executes at database level and return the results to our application.
In real world most application facing the performance issue which can be improved by code optimization. Here we will talk about the SQL query optimization.Most programming languages executes set of statements from Top to Bottom but SQL Server executes set of statements in a logical order which is uniquely decides by the SQL Server in a predefined order known as Logical Query processing phase.

Logical Query Processing Phase

When you write set of statements in a SQL query these set of statements divided into logical query processing phase. Each phase generates a series of virtual table feeding into the next phase. Virtual tables are not viewable. These Phases and their execution order are as below :
2. ON
11. TOP
As you can see above "FROM" clause executes first and then "ON" clause.

Let us take an example of join with where condition as you see "ON" executes first and then "WHERE" clause so if you are putting any condition in where clause it will be executed after joining the result so you have to put all the possible filter condition in "ON" clause for better optimized query since it executes before "WHERE" clause.
Let us take a query -
SELECT Salary*12 as CTC WHERE CTC > 500000
If you write above query and execute it in your query designer you will get the error that CTC is not a column defined. This is because in this query there is two clause "SELECT" and "WHERE" in which WHERE executes first and then SELECT so when you are referring CTC in WHERE it is not available cause SELECT clause has not even been executed at the time the WHERE clause is being run.

Let us take another example of OUTER JOIN with ON clause. "OUETR" clause executes subsequent to "ON" clause , so all rows eliminated by the "ON" clause will still be included in "OUTER" clause.

So next time when you are going to write query in SQL server take care of the execution order of SLQ clauses.

Happy reading!!

C# : What is New in C# 6.0?


In this post we will see the newly added features in C# 6.0. In C# 6.0 some very cool features has been added like "Auto-property Enhancements", "Primary Constructors", "Expressions as Function Body", "Use of Static", "Exception Filters", "inline declarations", "nameof Expressions", "Null-conditional Operators", "String interpolation", "Await in catch and finally".IntroductionHere, you will find nine new cool features of C# 6.0:Auto-property EnhancementsParameters on Classes and StructsUsing StaticException FiltersNull-conditional OperatorsIndex Initializers$ signString Interpolationnameof ExpressionAwait in catch and finally blockAuto-property EnhancementsYou can initialize the properties in the same way as you initialize variables, fields.public class Employee{public string FirstName { get; set; } = "Pankaj";public string LastName { get; set; } = "Maurya";}Parameters on Classes and StructsYou can pass the parameter to the classes/structs in the same way as you do with the methods/functions.public class Employee(string firstName, string lastName){public string FirstName { get; set; } = firstName;public string LastName { get; set; } = lastName;}You can also add the logic on parameters as:public class Employee(string firstName, string lastName){if (Equals(firstName,null)){throw new ArgumentNullException("firstName");}if (Equals(lastName,null)){throw new ArgumentNullException("lastName");}public string FirstName { get; } = firstName;public string LastName { get; } = lastName;}Using StaticIn C# 6.0, Microsoft announced a new behaviour to our CS compiler that allows us to call all the static methods from the static class without the name of the classes.Code in C# 5.0static void Main(string[] args){ Console.WriteLine("Enter first number :"); int num1 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter second number :"); int num2 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Multiplication : {0}", (num1 * num2)); Console.ReadLine();}Code in C# 6.0using static System.Console;using static System.Convert;public class UsingStaticTest{ static void Main(string[] args) { WriteLine("Enter first number :"); int num1 = ToInt32(ReadLine()); WriteLine("Enter second number :"); int num2 = ToInt32(ReadLine()); WriteLine("Multiplication : {0}", (num1 * num2)); ReadLine(); } }Exception FiltersWith this new feature, you can add conditional logic to catch block that decide which catch block will execute based on condition.try{throw new Exception("Pankaj");}catch (Exception ex) if (ex.Message == "Pankaj"){// this will execute because exception message matches.}catch (Exception ex) if (ex.Message == "Maurya"){// this will not execute because exception message does not match}Null-conditional OperatorsThe Null-Conditional operator is a new concept in C# 6.0 that automatically checks with null references. In previous version C# 5.0, if we are accessing any property of a class, then first we check the object of class with null and if not null, then reading the property but in C# 6.0, you can do the same with "?" operator.Code in C# 5.0namespace ConditionalTest{ class Program { static void Main() { Employee emp = new Employee(){ FullName = "Pankaj Maurya", EmpAddress = new Address() { ResidenceAddress = "New Ashok Nagar", OfficeAddress = "Udyog Vihar Pahse 2" } } if(emp!= null && emp.EmpAddress!=null) { WriteLine((emp.FullName) + " " + (emp.EmpAddress.ResidenceAddress??"No Address")); } ReadLine(); } } class Employee { public string FullName { get; set; } public Address EmpAddress { get[...]

Backbone – Basic Understanding of Model


Backbone ModelsWhen we talk about MVC pattern, Model becomes very important part of this. It is the Model which contains application data. The authors of backbone have quite a clear definition of what they believe the model represents in Backbone. Models are the heart of any JavaScript application, containing the interactive data as well as a large part of the logic surrounding it: conversions, validations, computed properties, and access control. What we have till now- In my last post Backbone, We have created a HTML page named main.html in which we had included the required script files. Let's create a new js file main and includes this file in our main.html page. Backbone js Tutorial Defining the Model- You can define the model by extending the Backbone.Model class.var Person = Backbone.Model.extend({ defaults:{ FName:"Manish", LName:"Dubey", Age : 28 }});In the above code , we are defining a model "TodoItem" with some default values like "FName" ,"LName" and "Age".Instantiating the Model- You can simply instantiate the model using new keyword.var person = new Person(); // will create the object of Person Model.Getters- In backbone, you can get the attribute values using the get method.person.get('Fname'); //will return the Fisrt name person.get(Age'); // will return Age valueSetter- You can also update the attribute values using set methodperson.set("FName", "Deepak"); // will update first nameperson.set("Age", 30); //will update AgeYou can also update the values in one go-person .set({FName:’Deepak’,Age:30});Deleting a Model- You can delete the model using destroy function.person.destroy();Json Output- Todoitem.toJSON() //This will return all attributes of that objectOutput on Browser Console- Now launch the main.html page in browser and run the above commands, you will get the below outputs.CodeProject[...]

Bacbone - An Introduction


What is Backbone ?Backkbone is a JavaScript library that let us create Single-Page Applications (SPAs) in structured manner. Backbone is based on Model-View-Controller (MVC) design pattern. It is suitable for creating Single-Page Applications (SPAs) using RESTful services for persisting data.Components in Backbone-Unlike traditional MVC which have three components, Backbone has following main components-ModelViewCollectionRoutersModel- Working on Data is the most important part of any application. Each application requires a to organise the Data in a structured way. Backbone Models provide us to manage all our entities. Backbone.Model by default provides the way to persists the data. Backbone.Model also provides the functionality to validate the data before persisting it.var SampleModel= Backbone.Model.extend({initialize : fuction(){};});View- Backbone Views used to display data model on UI. They are also used to listen the HTML element events and populating and rendering the views based on data.var SampleView=Backbone.View.extend({initialize : function(){};});Collection- Backbone Collections are simply a group of models. It can be used in situation such as-Model: Student Collection : ClasStudentsModel: Animals Collection: Zoovar SampleCollection= Backbone.Collection.extend({model : SampleModel});Routers- Backbone routers are used for routing your applications URL’s and execute code based on the requested URL and then render the view to the user.Set Up for Backbone-Backbone has a hard dependency on Underscore and soft dependency on jQuery. You need below libraries to include in your application-Backbone- You can download the Backbone from You can download this library from Download the jQuery library from downloading the above libraries include these library in your application's Main HTML page (here I have created main.html page). Backbone js Tutorial-Todo List ;CodeProject[...]

Difference between Stored Procedures and User Defined Functions in SQL Server


Stored Procedure
Stored Procedures are pre-compile objects which are compiled for first time and saved, which executes (compiled code) whenever it is called. Stored procedure does not necessarily return data, but it can return more than one result set. It can be used to affect data (update/insert/delete), can have transactions, can have error handling, do not have restrictions about non-deterministic functions, and can call other stored procedures.

User Defined Function
User defined function is compiled and executed every time when it is called. Function attempts to return something, always, and has several restrictions - for example, you can't use DML statements, call stored procedures, call NEWID(), etc. You also cannot have error handling, transactions, or non-deterministic functions (e.g. GETDATE() in SQL Server 2000).

Differences :
  • Stored procedures compiled first time and reuse the execution plan when next time called while function compiled every time when called.
  • Stored procedure can have input parameter as well as output parameter while user defined function can have only input parameters.
  • Stored procedure can return zero or n values while user defined function must return a value.
  • You can use SELECT as well as INSERT/UPDATE/DELETE (DML) statement in stored procedure whereas in User defined function you can use only SELECT statement.
  • Try-catch block as well as Transactions can be used in a stored procedure whereas neither try-catch block nor Transactions can be used in user defined function.
  • You can call use user defined function in SELECT statement as well as in the WHERE/HAVING section, cause it must return a value, while stored procedures can not be used in a SELECT statement as well as in the WHERE/HAVING section, cause it may or may not return value.
  • You can call user defined function in a stored procedure whereas stored procedures cannot be called within user defined function.
  • Stored procedure can use table variable as well as temporary table while user defined function can use only table variables, it will not allow using temporary tables.
  • User defined function can be used in join clause as a result set while stored procedures can’t be used in Join clause.

Conversion of Decimal to Binary in C#


In interviews, there are some programming questions which you will find most of the places like Write a program to reverse the string or Write a program to check string are palindrome or not etc..

In this post, I have a picked a question from that type of programming questions i.e.

Write a program for converting the decimal value to binary value?

Below is the simple method for converting a decimal value into binary value  :

Code Snippet

/// Method for converting Decimal to Binary

/// integer value
static string DecimalToBinary(int _value)
string strBinary = string.Empty;
while (_value >= 1)
strBinary = (_value % 2).ToString() + strBinary;
_value = _value / 2;
return strBinary;

Creating Batch file to Start and Stop the Window services


Windows  services are a very important part of windows environment. We can easily change the windows environment by stopping or starting the services, for example boost the system performance by stopping the multiple services during game playing.Warning: Manipulating windows services can have some unwanted effects on your system. You should create a system restore point before experimenting. We can easily changed the service state by creating batch file(.bat) having batch commands for start or stop the service. The important commands are the following- Net Stop- For stopping the service.Net Start- For Starting the service.Note:-The batch file will need to be run as administrator.For Example, I have taken the "Print Spooler" service to start through the batch file. Service name of "Print Spooler" service is "Spooler"."Print Spooler" Service before executing the batch file.Write the below command on the notepad and save the file with .Bat estension.       Net Start "Spooler"Execute the batch file as administrator."Print Spooler" Service after executing the batch file.I hope this article will be helpful for you. I would like to have any feedback from you. Your valuable feedback, question, or comments about this article are always welcome.[...]

Happy New Year 2014


Wish All of You a Very Happy and Prosperous New Year 2014 :)


How To- Load ASP.Net User Control Dynamically Using jQuery and Ajax


Here in this post, I am going to explain how to dynamically load the Asp.Net user control using jQuery and Ajax. For loading the user control we will use the Web Method on server side and call that web method through Ajax call using jQuery.You can also find my other articles related to C#, ASP.Net,  jQuery, Java Script and SQL Server.So, lets start the example. In this example I have used one aspx page name Demo.aspx and one user control to load on the aspx page DemoUserControl.ascx.ASPX Page
User Control Content
In the above aspx page, there are two TextBoxes for capturing the input and one Button to load the user control and show the enterd value.User Control Mark Up<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="DemoUserControl.ascx.cs" Inherits="LoadUserControlByjQuery.DemoUserControl" %>
In the above mark up there are two Label with id lblNameValue and lblAgeValue. These label will be used to show the enterd value after loading the user control on aspx page.C# Code on ASPX PageWrite the following web method into ASPX page code behind file.[WebMethod]public static string LoadUserControl(string name, int age){ using (Page _page = new Page()) { //Load the user control UserControl usrControl = (UserControl)_page.LoadControl("DemoUserControl.ascx"); //Set the name and age parameter values to User Control's respective labels (usrControl.FindControl("lblNameValue") as Label).Text = name; (usrControl.FindControl("lblAgeValue") as Label).Text = age.ToString(); _page.Controls.Add(usrControl); using (StringWriter writer = new StringWriter()) { _page.Controls.Add(usrControl); HttpContext.Current.Server.Execute(_page, writer, false); return writer.ToString(); } }}Now add the following java script code into head section of ASPX page.Script Code