Gil Gil - 2 months ago 8
ASP.NET (C#) Question

How to retrieve data from mssql database into json code with asp.net

I have a website coded in asp.net and a mssql database.

I want to retrieve data located in my database with json and print it inside a div. The site is using jQuery mobile. I need it to work asynchronously.

This is DataFetch.aspx that should fetch the data from the database and print it in json format:

<%
UserDB udb = new UserDB();
Users u = udb.SelectById((int)Session["loggedID"]);
TestDB tdb = new TestDB();
Tests t = tdb.SelectByStudentID((int)Session["loggedID"]);

//QueryString["task"] = 1 => Fetch Grades
if (int.Parse(Request.QueryString["task"]) == 1)
{

Response.Write("{ \"grades\":");
for (int i = 0; i < t.Count; i++)
{
if (i != 0)
Response.Write(",");

Response.Write(" [{\"subjectName\":\"" + t[i].lesson + "\", \"date\":\"" + t[i].date + "\", \"grade\":\"" + t[i].grade + "\"}]");
}
Response.Write(" }");
}


That's the resulting json:

{ "grades": [{"subjectName":"Math", "date":"18/09/2016", "grade":"100"}] }


And this is how I read and interpret the json code written in DataFetch.aspx:

var xhttp = new XMLHttpRequest();
var jsonResult;
xhttp.onreadystatechange = function () {

if (this.readyState == 4 && this.status == 200) {
jsonResult = JSON.parse(this.responseText);
document.write(jsonResult.grades[0].subjectName);
}
}
xhttp.open("GET", "DataFetch.aspx?task=" + task, true);
xhttp.send();
};


"this.responseText" includes the html markups and everything. Is there an elegant way to fix it?

Answer

You can get datas from aspx page using web method by using ajaxcall

 [WebMethod]
public static string OnGetData(string task)
{
 //////
 return  jsonResult; /// your json data
}
   <script type="text/javascript">

$(function() {
    var mytask = task;
    $.ajax({
        type: "POST",
        url: "DataFetch.aspx/OnGetData",
        data: "{task:" + mytask + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
          ///your code
       }
    });
});
</script>