Wednesday, 20 November 2013

JSON With Web Service AJAX Call In c# Asp.NET

here i have created on service and called that service with use of ajax function from javascript.

the service is returning list as json

data to ajax function as a result.

(i have just explain you a basic example, you can return what ever you want to return)

 

WebService1.asmx.cs File

This file is having service method

 
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data;
using System.Web.Script.Services;
using System.Runtime.Serialization;
using Newtonsoft.Json;     ///Add the reference of JSON.NET Dll for the json converter used in program



namespace TestJavascriptServices
{
    /// <summary>
    /// Summary description for WebService1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public String HelloWorld()
        {


            Hashtable ht = new Hashtable();
            ht.Add("me", "jayesh");
            ht.Add("you", "CPU");
            ht.Add("My", "Mind");
            ht.Add("Your", "Processor");
            ht.Add("And", "Blast");

            List<String> ls = new List<string>();
            ls.Add("Jayesh");
            ls.Add("Jayesh1");
            ls.Add("Jayesh2");
            ls.Add("Jayesh3");
            ls.Add("Jayesh4");
            Test t = new Test();

            t.setData("me", "jayesh");
            
            //return "{\"me\":\"Hello this is jayesh\",\"u\":\"hsdh\",\"t\":\"dhdsfh\",\"s\":\"dsfhsdjh\"}";
            return JsonConvert.SerializeObject(t.getData());
            //return JsonConvert.SerializeObject(ls);
            //return JsonConvert.SerializeObject(ht);
            //return JsonConvert.SerializeObject(t);


        }
    }

    public class Test {
        public string Name;
        public string salary;

        public void setData(string n,string s)
        {
            this.Name = n;
            this.salary = s;
        }

        public Test getData() {
            return this; 
        }
      
    }

}


TestWebServiceHello.js

This file is having ajax functions which will call service 



var test;
function pageLoad() 
{
    test = new TestJavascriptServices.WebService1();
    test.set_defaultSucceededCallback(SucceededCallback);
    test.set_defaultFailedCallback(FailedCallback);
}


function SucceededCallback(result) {
    var RsltElem = document.getElementById("Results");

    var dd = $.parseJSON(result);
    alert(dd);
    RsltElem.innerHTML = dd.me;
}

function calll() {
alert("here");
    var greetings = test.HelloWorld();

}

function FailedCallback(error, userContext, methodName) {
    if (error !== null) {
        var RsltElem = document.getElementById("Results");

        RsltElem.innerHTML = "An error occurred: " +
            error.get_message();
    }
}

if (typeof (Sys) !== "undefined") Sys.Application.notifyScriptLoaded();

Default.aspx

This file is having html inputs

 

 
<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="TestJavascriptServices._Default" %>




<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js" ></script>
<asp:ScriptManager runat="server" ID="scriptManager">
                <Services>
                    <asp:ServiceReference path="~/WebService1.asmx" />
                </Services>
                <Scripts>
                    <asp:ScriptReference Path="~/TestWebServiceHello.js" />
                </Scripts>
            </asp:ScriptManager>

    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit <a href="http://www.asp.net" title="ASP.NET Website">www.asp.net</a>.
    </p>
    <p>
        You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&amp;clcid=0x409"
            title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>.
    </p>
    <span id="Results"></span>

    <input type="button" id="btn" onclick="calll();return false;" value="Click me" />






Download   
Newtonsoft plugin from here and add the reference to the project file

http://james.newtonking.com/json


No comments:

Post a Comment