BR BHARDWAJ
BR BHARDWAJ

Reputation: 409

how to bind my dropdownlist by json result?

my json string in developer tool network tab is:

"{\"1\":\"GJ_CITY1\",\"2\":\"GJ_CITY2\",\"3\":\"GJ_CITY3\",
  \"4\":\"GJ_CITY1\",\"5\":\"Aman\",\"6\":\"Aman\",
  \"7\":\"Aman\",\"8\":\"Aman\",\"9\":\"Alwar\"}"

i saw various articles but that doesn't work ,i am new to ajax data bindig and my mvc code is

$.ajax({
        type:"GET",
        datatype:"JSON",
        url: queryLink,
        async: true,
        success: function (result) {

            $('#Cities').html("");//clear before bind
            $.each(result, function (i, Cities) {
                $("#Cities").append($('<option value=\"" + key + "\">" + val + "</option>'));
            });
        }
});

my controller code is

 CitiesDao cities_obj = new CitiesDao();
        HybridNetworkHandoverdto obj = new HybridNetworkHandoverdto();
        var query1 = cities_obj.Details().Tables[0].AsEnumerable().Select(t => new CityDto
        {
            State_id = t.Field<long>("state_id"),
            State_name = t.Field<string>("state_name"),
            City_id = t.Field<long>("City_id"),
            City_name = t.Field<string>("City_name")
        }).ToList();
        ViewBag.cities = query1;
        Dictionary<string, string> abc = new Dictionary<string, string>();
        foreach (var item in query1)
        {
            abc.Add(item.City_id.ToString(),item.City_name);
        }

        //string jsonResult = JsonConvert.SerializeObject(abc);
        var jsonResult = new JavaScriptSerializer();
        var json = jsonResult.Serialize(abc);


        return Json(json, JsonRequestBehavior.AllowGet);

Upvotes: 3

Views: 1516

Answers (2)

BR BHARDWAJ
BR BHARDWAJ

Reputation: 409

$.each(result, function (i, value) {
    var html='<option value="'+i+'">' + value + '</option>'
    $("#Cities").append(html);
});

this works but i have to use JSON.parse() as @MKA suggested i don't know why it works with Json.parse()

i am using stephens answer btw.

Upvotes: 1

Rohit Kumar
Rohit Kumar

Reputation: 1958

Do it a as below -

$.each(result, function (i, value) {
    var html='<option value="'+i+'">' + value + '</option>'
    $("#Cities").append(html);
});

Upvotes: 2

Related Questions