webservice code:
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public void GetDatBooth()
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
String resultJSON = "";
JavaScriptSerializer js = new JavaScriptSerializer();
try
{
Context.Response.Clear();
Context.Response.ContentType = "application/json";
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Dictionary<String, Object>> tableRow = new List<Dictionary<string, object>>();
Dictionary<String, Object> rows;
DataTable dt = new DataTable();
dt.TableName = "Mytab";
dt.Columns.Add("BoothNo");
dt.Columns.Add("VotingQue");
dt.Columns.Add("Percentage");
DataRow dr = dt.NewRow();
dr["BoothNo"] = "01";
dr["VotingQue"] = "14";
dr["Percentage"] = 14;
DataRow dr1 = dt.NewRow();
dr1["BoothNo"] = "02";
dr1["VotingQue"] = "12";
dr1["Percentage"] = 12;
dt.Rows.Add(dr);
dt.Rows.Add(dr1);
foreach (DataRow dr3 in dt.Rows)
{
rows = new Dictionary<string, object>();
int i = 1;
foreach (DataColumn col in dt.Columns)
{
rows.Add(col.ColumnName, dr3[col].ToString());
i = i + 1;
}
tableRow.Add(rows);
}
resultJSON = serializer.Serialize(tableRow).ToString();
}
catch (Exception ex)
{
resultJSON = ex.Message.ToString();
}
Context.Response.Write(resultJSON);
}
Ajax call code:-
<script type="text/javascript">
$(function () {
$.ajax({
url: 'WebService.asmx/GetDatBooth',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
success: function (data, status) {
alert(data);
}
});
});
</script>
What I have tried:
how to call webservice json data through ajax/json