Populating C# Object in JavaScript

With the evolution of AJAX and async http request and of course jQuery instead of full post back to server , async call to server is most preferred. It is also providing user a better web experience.
So in this post I am going to explain how you can fill your C# object via your client side code. In web market lot of scripting framework available through which you can create a better framework for your project where you don't have to deal with any server side code such as Angular JS which provides an client side MVC framework. But in case in your project which is not an MVC but simple asp.net application, then this blog post is going t be more beneficial to you.
Lets take the case you have an application which is calling a web service method which is written in your page server code or lets take this way that instead of clicking button and post your data to server using full post back you want to achieve this functionality using Java Script async or AJAX call without using AJAX Control Toolkit for ASP.NET AJAX. So in this case lets create a simple class which we will be using for data Transfer. Lets Name is Employee.

1:  public class Employee  
2:  {  
3:  public string EmpName{get;set;} // Property of type string  
4:  public Address EmpAddress{get;set;} // Property of type Address   
5:  public int64 EmpNumber{get;set;} // property of type long  
6:  public double Salary{get;set;} // property of type double  
7:  public DateTime DateOfBirth{get;set;} // property of type Date Time  
8:  public bool IsActive{get;set;} // property of type boolean 
9:  public List Interest{get;set;} // property of type collection
10:  }  
11:  public class Address  
12:  {  
13:  public string Street{get;set;}  
14:  public string City{get;set;}  
15:  public string State{get;set;}  
16:  public string Country{get;set;}  
17:  public int ZipCode{get;set;}  
18:  }  

Now suppose you have an aspx page which is taking value from the user via from fields and filling into the above class object. If you observe above class then I have taken almost all types such as object ,int , string , list so that everything get clear at this stage without any confusion.
You all know we can not call the simple methods of the aspx page from client via ajax call. So for this we need to add some attributes on the method which is [WebMethod] used in web services which will allow client side code to directly interact with the service side methods directly.
Note : In order to access web methods from client side, method must be static else it will not be visible to client code and will throw run time exception..
Lets create an aspx page with name Employee.aspx and add below method in your page server side code
1:  [WebMethod]  
2:  public static string SaveEmployee(Employee emp)  
3:  {  
4:  // process your code here for saving the data to your database  
5:  }  

Now the most important part of this blog post is to call the above defined web method from the client side. I am not going to create the full form with the fields here. Suppose we already have all the required fields and we have a submit button on click of this button we need to call this method. Also you must include the jquery library reference to your page. lets see the below code for the processing.
1:  $(document).ready(function () {  
2:        $('#btnSaveEmployee').click(function () {  
3:            var empData= GetEmpData();  
4:            $.ajax({  
5:              type: "POST",  
6:              url: "Employee.aspx/SaveEmployee",  
7:              data: JSON.stringify({ 'emp': empData}),  
8:              contentType: "application/json; charset=utf-8",  
9:              dataType: "json",  
10:              async: true,  
11:              cache: false,  
12:              success: function (msg) {  
13:                if (msg.d == "Success") {  
14:                    //Do whatever you want to do after success .. :)  
15:                } else {  
16:                  //Do whatever you want to do ... :)  
17:                }  
18:              },  
19:              error: function (x, e) { // Show message in case of any exception }  
20:            });  
21:            return false;  
22:        });  
23:      });  

Lets analyze the above code we have written. I have called a function GetEmpData(); method in which I will fill the Employee object. Now the main things we need to keep in mind that the url which we must use should be the name of the aspx page and then the web method which we defined in the server side code and in data we are converting the javascript object to JSON object using JSON.stringify and passing the object. Also keep in mind that the parameter name should be same as in the method we defined. here we used parameter name as 'emp'.
Now lets create the method to fill the object.

1:  function GetEmpData() {
2:        var empdata= {
3:                      EmpName: "Dharmendra Kumar",
4:                      EmpAddress: {
5:                                     Street: "Your Street",
6:                                     City: "Your City",
7:                                     State: "Your State",
9:                                     Country: "Your Country",
10:                                    ZipCode: "Your Zip"
11:                                 },
12:                    EmpNumber: "Your Data",
13:                    Salary: "Your Salay",
14:                    DateOfBirth: "You DOB",
15:                    IsActive: "true/false",
16:                    Interest: [{"Intereste1"},{"Interest2"},....... so on]
17:                   };
18:      return empdata;  
19: }

In the above code we have filled the C# object and each data is filled as string whatever the type is in c#. If you will run the above code it will send the filled object to server where you can process your data.
Hope it will help you in your projects / works. Any suggestions / comments are welcome to improve the quality of this post.

Comments