I want to retreive the data from database and assign it to dropdownlist. For that I'm using the following jquery in the onclick event
function getcountry() {
try {
$.ajax({
type: "POST",
url: "/JsonWebServiceWithJQuery/jsonwebservice.asmx/getcountry",
data: "{}",
contentType: "application/json;charset=utf-8",
success: ajaxCallSucceed,
datatype: "json",
failure: ajaxCallFailed
});
}
catch (e) {
alert("Failed calling webservice" + e);
}
}
function ajaxCallSucceed(response) {
alert("Success");
alert(response.d);
}
function ajaxCallFailed(error) {
alert("I'm failed");
alert('error: ' + error);
}
<input type="button" value="Get All Users" onclick="getcountry();" />
This is the webmethod I'm using for retreiving from database and also a conversion function to convert datatable into json format. It is retreiving correctly. But, the output is coming as undefined. I can't fix the bug.. Any help?
public static string CreateJsonParameters(DataTable dt)
{
StringBuilder JsonString = new StringBuilder();
//Exception Handling
if (dt != null && dt.Rows.Count > 0)
{
JsonString.Append("[ ");
JsonString.Append("{ ");
for (int i = 0; i < dt.Rows.Count; i++)
{
JsonString.Append("{ ");
for (int j = 0; j < dt.Columns.Count; j++)
{
if (j < dt.Columns.Count - 1)
{
JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\",");
}
else if (j == dt.Columns.Count - 1)
{
JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\"");
}
}
/*end Of String*/
if (i == dt.Rows.Count - 1)
{
JsonString.Append("} ");
}
else
{
JsonString.Append("}, ");
}
}
JsonString.Append("}]");
return JsonString.ToString();
}
else
{
return null;
}
}
public static string getcountry()
{
country c = default(country);
List<country> cntrylist = new List<country>();
DataTable dt = new DataTable("table1");
using (SqlConnection connection = new SqlConnection(connectionstring))
{
using (SqlDataAdapter da = new SqlDataAdapter("getcountry", connection))
{
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.Fill(dt);
connection.Close();
string s = CreateJsonParameters(dt);
return s;
}
}
}