Currently I have an AJAX request which will run the following SQL statement.
select top 1
DrugQuestionId
,DrugId
,DrugQuestion as DrugQuizquestion
,CorrectAnswer
,QuizQuestionTypeId
from DrugQuestions
and return me one drugQuestion object, with the properties listed in the SQL Server table.
pertinent JS:
$(document).ready(function ()
{
$('#btnSubmit').click(function ()
{
$.ajax(
{
type: "POST",
url: "GetDrugQuiz.asmx/GenerateDrugQuestion",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data)
{
var drugQuestion = $.parseJSON(data.d);
//everything prints to the console correctly
console.log(drugQuestion.DrugQuestionId); //5 in this example
console.log(drugQuestion.DrugId);
console.log(drugQuestion.DrugQuizQuestion);
console.log(drugQuestion.CorrectAnswer);
console.log(drugQuestion.QuizQuestionTypeId);
},
error: function (xhr)
{
alert(xhr.status);
}
});
});
});
This works fine and gives me the answer I was looking for. In practice, I need a drugQuiz object which has a property which is an array of drugQuestion objects. I used the following WebMethod to attempt that:
//this is questions, plural mean to populate an array with a length equal to the row count
//of the query
public string GenerateDrugQuestions()
{
var jss = new JavaScriptSerializer();
DrugQuiz qz = new DrugQuiz();
qz.PatientId = 123;
qz.DateTaken = DateTime.Now;
qz.DrugQuizId = 1;
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
using (var con = new SqlConnection(cs))
{
using (var cmd = new SqlCommand("select top 3 * from DrugQuestions", con))
{
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
DrugQuestion dq = new DrugQuestion();
dq.DrugQuestionId = (int)rdr["DrugQuestionId"];
dq.DrugId = (int)rdr["DrugId"];
dq.DrugQuizQuestion = rdr["DrugQuestion"].ToString();
dq.CorrectAnswer = rdr["CorrectAnswer"].ToString();
dq.QuizQuestionTypeId = (int)rdr["QuizQuestionTypeId"];
qz.DrugQuestions.Add(dq);
}
return jss.Serialize(qz);
}
}
}
So you can see that a JSON string is being returned from the WebMethod. When I use the WebMethod without actually visiting the page and hit Invoke, I get the correct string. What I can't figure out is how to populate an array of drugQuestions, which is a property of a drugQuiz object. What do I need to change about the following code to allow that to happen?
$(document).ready(function ()
{
var drugQuiz = {};
drugQuiz.drugQuestions = new Array();
$('#btnSubmit').click(function ()
{
$.ajax(
{
type: "POST",
url: "GetDrugQuiz.asmx/GenerateDrugQuestions",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data)
{
drugQuiz.drugQuestions.push($.parseJSON(data.d));
console.log(drugQuiz.drugQuestions.length);
console.log(drugQuiz.drugQuestions);
},
error: function (xhr)
{
alert(xhr.status);
}
});
});
});
I need to be able to do something like alert(drugQuiz.drugQuestions[0].DrugId);