11

I have a WebMethod which gets data that I want to fill DropDown with in a DataSet. Currently I am filling the dropdown using a hardcoded object. But I want to replace this hard coded object with data returned by webmethod.

 [System.Web.Services.WebMethod]
         public static string GetDropDownDataWM(string name)
         {
             //return "Hello " + name + Environment.NewLine + "The Current Time is: "
             //    + DateTime.Now.ToString();

             var msg = "arbaaz";

             string[] name1 = new string[1];
             string[] Value = new string[1];
             name1[0] = "@Empcode";
             Value[0] = HttpContext.Current.Session["LoginUser"].ToString().Trim();
             DataSet ds = new DataSet();
             dboperation dbo = new dboperation();
             ds = dbo.executeProcedure("GetDropDownsForVendor", name1, Value, 1);

             return ds.GetXml(); 

         }

CLIENT SIDE(UPDATE 1):

  <script type = "text/javascript">
    function GetDropDownData() {
        var myDropDownList = $('.myDropDownLisTId');

        $.ajax({
            type: "POST",
            url: "test.aspx/GetDropDownDataWM",
            data: '{name: "abc" }',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                $.each(jQuery.parseJSON(data.d), function () {
                    myDropDownList.append($("<option></option>").val(this['FieldDescription']).html(this['FieldCode']));
                });
            },
            failure: function (response) {
                alert(response.d);
            }
        });
    }
    function OnSuccess(response) {
        console.log(response.d);
        alert(response.d);
    }
</script>
2
  • what is your response look like? Commented Apr 9, 2014 at 7:45
  • @Arbaaz, does the code that you have edited (in your Q) work? Commented Sep 29, 2014 at 15:44

5 Answers 5

20
function GetDropDownData() {
    $.ajax({
        type: "POST",
        url: "test.aspx/GetDropDownDataWM",
        data: '{name: "abc" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data.d)
                {
                    $.each(data.d, function (){
                        $(".myDropDownLisTId").append($("<option     />").val(this.KeyName).text(this.ValueName));
                    });
                },
        failure: function () {
            alert("Failed!");
        }
    });
}
Sign up to request clarification or add additional context in comments.

Comments

1
 var theDropDown = document.getElementById("myDropDownLisTId");
                theDropDown.length = 0;
                $.each(items, function (key, value) {

                    $("#myDropDownLisTId").append($("<option></option>").val(value.PKId).html(value.SubDesc));

here "SubDesc",PKId describes the value getting out of Database., u need to separate your value from dataset.

Comments

1

From the WebMethod, don't send DataSet directly, send XML...

[System.Web.Services.WebMethod]
public static string GetDropDownDataWM(string name)
{
    DataSet ds = new DataSet();
    ds.Tables.Add("Table0");
    ds.Tables[0].Columns.Add("OptionValue");
    ds.Tables[0].Columns.Add("OptionText");
    ds.Tables[0].Rows.Add("0", "test 0");
    ds.Tables[0].Rows.Add("1", "test 1");
    ds.Tables[0].Rows.Add("2", "test 2");
    ds.Tables[0].Rows.Add("3", "test 3");
    ds.Tables[0].Rows.Add("4", "test 4");

    return ds.GetXml();
}

Before Ajax call...

var myDropDownList = $('.myDropDownLisTId');

Try like below...(inside Ajax call)

success: function (response) {
    debugger;

    $(response.d).find('Table0').each(function () {
           var OptionValue = $(this).find('OptionValue').text();
           var OptionText = $(this).find('OptionText').text();
           var option = $("<option>" + OptionText + "</option>");
           option.attr("value", OptionValue);

           myDropDownList.append(option);
     });
},

Note:

  1. OptionValue and OptionText are the Columns of DataSet Table.

  2. $(response.d).find('Table0').each(function (){}) - Here Table0 is the name of Table inside DataSet.

17 Comments

But where do I call the GetDropDownData()? In filldd() right?
@Arbaaz Yes, in that filldd() function.
Failed to load resource: the server responded with a status of 500 (Internal Server Error
look at his fiddle .. jsfiddle.net/a4NSm/5 I want to fill the dropdown with data returned by server instead of hardcoded object.
500 Errors means that the URL is wrong. Are you sure that URL test.aspx/GetDropDownDataWM is correct?
|
0
[System.Web.Services.WebMethod]
     public static string GetDropDownDataWM(string name)
     {
         //return "Hello " + name + Environment.NewLine + "The Current Time is: "
         //    + DateTime.Now.ToString();

         var msg = "arbaaz";

         string[] name1 = new string[1];
         string[] Value = new string[1];
         name1[0] = "@Empcode";
         Value[0] = HttpContext.Current.Session["LoginUser"].ToString().Trim();
         DataSet ds = new DataSet();
         dboperation dbo = new dboperation();
         ds = dbo.executeProcedure("GetDropDownsForVendor", name1, Value, 1);

         return DataSetToJSON(ds); 

     }

public static string DataSetToJSON(DataSet ds)
{

    Dictionary<string, object> dict = new Dictionary<string, object>();
    foreach (DataTable dt in ds.Tables)
    {
        object[] arr = new object[dt.Rows.Count + 1];

        for (int i = 0; i <= dt.Rows.Count - 1; i++)
        {
            arr[i] = dt.Rows[i].ItemArray;
        }

        dict.Add(dt.TableName, arr);
    }

    var lstJson = Newtonsoft.Json.JsonConvert.SerializeObject(dict);
    return lstJson;
}

Ajax Call

function GetAssociation() {

        var myDropDownList = $("#myDropDownLisTId");
        var post_data = JSON.stringify({ "name": "xyz"});
        $.ajax({
            type: "POST",
            url: "test.aspx/GetDropDownDataWM",
            data: post_data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                json_data = JSON.parse(response.d);
                myDropDownList.empty();
                for(i=0; i<json_data.Table.length; i++)
                {

                    myDropDownList.append($("<option></option>").val(json_data.Table[i][0]).html(json_data.Table[i][1]));
                }

            },
            failure: function (response) {
                alert(response.d);
            }
        });
    }

Comments

0
// We can bind dropdown list using this Jquery function in JS script
   

function listDropdownBind() {
  var requestId = 123; 
    $.ajax({
        type: "POST",
        url: "/api/ControllerName/ActionName?param=" + param, // call API with parameter
        headers: { 'rId': requestId },
        dataType: "json",
        contentType: "application/json; charset=utf-8",

        success: function (data) {
            var optionhtml1 = '';
            var optionhtml1 = '<option value="' +
                0 + '">' + "--Select--" + '</option>';
            $("#ddlName").append(optionhtml1);

            $.each(data, function (i) {

                var optionhtml = '<option value="' +
                    data.d[i].Value + '">' + data.d[i].Text + '</option>';
                $("#ddlName").append(optionhtml);
            });
        }
    });
};

1 Comment

A good answer will always include an explanation why this would solve the issue, so that the OP and any future readers can learn from it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.