Below is the step by step to create webservice:
- Open Visual studio.
- Create New Project
- Add New File in the solution and choose Web Service file( .asmx)
- Copy paste code below to create your own JSON webservice
The Web Service Code
/// <summary>
/// Summary description for KenticoJSONTest
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class AjaxWebService : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public String getState(string Country)
{
string retJSON = "";
SqlConnection dbConn = new SqlConnection("<Connection String>");
SqlDataAdapter dbAdapter = null;
string sql = "SELECT STATE_FULL_NAME,STATE_SHORT_NAME FROM STATE WHERE COUNTRY LIKE '%" + Country + "%'";
DataTable returnTable = new DataTable("State");
dbConn.Open();
dbAdapter = new SqlDataAdapter(sql, dbConn);
dbAdapter.Fill(returnTable);
dbConn.Close();
retJSON = GetJson(returnTable);
return retJSON;
}
private string GetJson(DataTable dt)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Dictionary<string, object>> rows =
new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName.Trim(), dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
}
Example Output
"[{"FULL_NAME":"NEGERI SEMBILAN","SHORT_NAME":"N. SEMBILAN"},{"FULL_NAME":"WILAYAH PERSEKUTUAN KUALA LUMPUR","SHORT_NAME":"KUALA LUMPUR"},{"FULL_NAME":"MELAKA","SHORT_NAME":"MELAKA"}]"
By Mohd Zulkamal
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
0 comments:
Post a Comment