Saturday, 9 June 2012

how to fill listbox in aps.net using json and jquery

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
    <script language="javascript" type="text/javascript">
        $(document).ready
    (
    function () {
        $('#ddl').change
    (
    function () {
        alert($('#ddl >option:selected').val())
    }
    )
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "WebService.asmx/x",
            data: "",
            dataType: "json",
            async: false,
            success: function (data) {
                $('#ddl > option').remove();
                for (var i = 0; i < data.d.length; i++) {
                    $('<option/>').text(data.d[i].NAME).val(data.d[i].EID).appendTo('#ddl')

                }

            }
        });
    }
    )
    </script>
</head>
<body>
    <form id="form1" >
    <div align="center">
   <select id="ddl" size="3" style="width:200px"></select>
    </div>
    </form>
</body>
</html>

Webservice Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;


[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

    DataClassesDataContext o = new DataClassesDataContext();
    public WebService ()
    {

      
    }

    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }
    [WebMethod]
    public List<EMP> x()
    {
        return o.EMPs.ToList();
    }

No comments:

Post a Comment