As many of you have probably experienced, it becomes necessary from time to time to implement a custom SharePoint application page and to retrieve data from the server via jQuery and/or a Web Service. As it happens, when data on the server side is in an object state, it will be serialized and the data will interact with the browser as a JSON format string. However, when the data is on the client side, the string needs to be deserialized to the client object, which is something you can use jQuery to accomplish.
In this blog post, we’ll introduce you to the steps needed to serialize an object state to JSON format, as well as how to deserialize an object to the client side.
Create an Empty SharePoint Project:
- To begin, open Microsoft Visual Studio and go to File > New > Project.
- Under Installed Templates in your Project Types menu, go to Visual C# > SharePoint > 2010 and select Empty SharePoint Project.
- Input the Name of the project as well as its location, Solution (in this example, we’ll create a new solution), and Solution Name.
- Click OK:
Implement “Define Object Class” to Serialize:
- In your project, you will need to define an object class that will respond back to the client. In this example, the objects we will be creating will be a company’s employees:
Implement Web Service to Speak with the Client Side:
- To begin, add a Web Service in the Layouts folder.
- Next, implement a service that will process client call requests:
- In Web Service, implement a Web method that will identify the object mode and deserialize it so that it will be responsive to the JSON data string format:
- To serialize the object state to a state that is compatible with a JSON data string format, use the JavaScriptSerializer class in C#:
- To use JavaScriptSerialization, you must add a reference to the following DLL extension: System.Web.Extensions.dll.
- Using the Serializer, you will now be able to receive an object as a data string in JSON format. You will now be positioned to finalize your backend implementation.
Build the aspx Page and Client Script:
Your next step will be to build a client script from which you will be able to both derive value from the Web Service as well as display the information in your browser.
- In the Layout folder, add a SharePoint application page. In this example, we will be adding four textbox controls that will display each employee’s properties.
- At the end of the Employee information form, add an asp:Button:
- From there, input a function that will allow you to programmatically implement client callbacks:
Deploy your custom page:
- Navigate to the SharePoint page you created above:
- Click on the Get User button. Using jQuery’s Ajax, it will call and fetch data from the Web Service. The object that is returned from the Web Service will be deserialized using jQuery. The object’s properties will now be displayed on the form on your custom SharePoint page: