Reputation:
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: '/Umbraco/api/RegisterUser/GetCountry',
type: 'GET', // You can use GET
data: '{}',
dataType: "json",
context: this,
success: function (data) {
alert(data);
$.each(data, function (key, item) {
$('#ddcountry').append(
$("<option></option>")
.attr("value", item.Country_name)
.text(item.Country_name)
);
});
alert("success");
},
error: function (request) {
alert("error");
}
});
});
My code return on URL path is
[HttpGet]
public string GetCountry()
{
String daresult = null;
DataSet ds = new DataSet();
DataTable dt = new DataTable();
DataTable dt1=new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter("SELECT countryid,country_name FROM country_master", UmbracoConnectionString))
{
da.Fill(dt1);
}
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>(10);
Dictionary<string, object> row;
foreach (DataRow dr in dt1.Rows)
{
DataRow[] dr1 = dt1.Select("countryid=" + dr["countryid"]);
if (dr1.Count() > 0)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt1.Columns)
{
if (col.ColumnName == "country_name")
{
row.Add(col.ColumnName, dr[col]);
}
}
rows.Add(row);
}
}
return serializer.Serialize(rows);
}
My HTML code is below where i had inserted some of the data manually
Country:<select id="ddcountry">
</select>
But by doing all this things **how should I fill my dropdown with retriving data as data shown in below image
On alert of data i am getting data as below
Upvotes: 0
Views: 102
Reputation: 1427
try this
$(document).ready(function () {
$.ajax({
url: '/Umbraco/api/RegisterUser/GetCountry',
type: 'GET', // You can use GET
data: '{}',
dataType: "json",
context: this,
success: function (data) {
var options = "";
$.each(data, function(i, item) {
options += '<option value="'+item.id+'">'+item.label+'</option>';
});
$('#ddcountry').append(options);
},
error: function (request) {
alert("error");
}
});
});
Upvotes: 0
Reputation: 1391
I guess, It will solve your issue:
First, You need to convert your JSON String to JSON Array and Then Iterate it to dynamically create options
for your select
dropdown.
var res = jQuery.parseJSON(data);
$.each(res , function (key, item) {
$('#ddcountry').append(
$("<option></option>")
.attr("value", item.country_name)
.text(item.country_name)
);
});
Upvotes: 1
Reputation: 3399
Something like this in the success section:
$.each(data, function(i, item) {
$('#yourDiv').find('#yourSelect')
.append($('<option>', { value: item['yourID'],
text: item['yourText'] }));
});
Also try doing this in your class:
//daresult = DataSetToJSON(ds);
return Json(daresult);
Upvotes: 0