Eran Hefer

Eran Hefer

  • NA
  • 3
  • 0

Passing JavaScript objects to the server using Ajax.Net Professional

Sep 27 2007 1:45 PM

Posted by, Eran Hefer.

As you may already know, with Ajax we can easily pass simple or custom object from the server to the client.

In this article, I'll show a way to do the opposite: passing JS objects from the client code, to the server (Ajax method).

Here is the client (JavaScript) Code:

    //The JavaScript client side function

    function PassToServer()

    {

        //declare the new JS object

        var student = new Object();

       

        //insert some values

        student.First_Name = "Jon";

        student.Last_Name = "Smith";

        student.Grade = 100;

       

        //pass the JS object to the server.

        //'JSobjects' is the page name.

        //'GetFromClient' is the ajax method name on the server.

        var bothNames = JSobjects.GetFromClient(student).value;

       

        //display the returned value from the server

        alert(bothNames);

    }

Here is the Server (C#) Code:

    //The Ajax method on the server side

    [AjaxPro.AjaxMethod]

    public string GetFromClient(AjaxPro.JavaScriptObject jsObject)

    {

        //get the data members values from the JavaScript object.

        //the 'Key' is the name of the data member that was declared at the client.

        //we need to remove the " from the string value.

        string first_name = jsObject["First_Name"].Value.Replace("\"","");

        string last_name = jsObject["Last_Name"].Value.Replace("\"", "");

        int grade = Int32.Parse(jsObject["Grade"].Value);

 

 

        //return back the first name + last name.

        return first_name + " " + last_name;

    }

Note that you must download the Ajax.NET Professional framework to use this code.