Witam,
Próbuję sobie przesłać dane z bazy do javascriptu, aby potem już nie pobierać danych tylko zrealizować sobie quiz w js, po stronie klienta.
Skrypt działa, pojawią się quizy.
@section Scripts{
<script type="text/javascript">
$(document).ready(function() {
$('#btnGetQuizzes').click(function() {
$.getJSON("/Test/GetJsonAllQuizzes", null, function(data) {
var div = $('#ajaxQuizzes');
div.html("<br/> " + "Quizzes received from server: " + "<br/>");
$.each(data, function(i, item) {
printQuizzes(div, item);
});
});
});
});
function printQuizzes(div, item) {
div.append("<br/>" + "Nazwa: " + item.Title);
}
</script>
Drugi skrypt, która ma pobrać pytania z danego quizu. Nic nie wyświetla, pewnie przez tą jedynkę: Test/GetJsonAllQuestions/1 jak przekazać id do kontrolera, na razie chce ręcznie wpisać na próbę czy zadziała. Z Jsona otrzymam listę pytań typu Question z takimi samymi polami jak w C#, na której potem w js będę mógł wyświetlić jej dowolny element, dobrze to rozumiem?
<script type="text/javascript">
$(document).ready(function () {
$('#btnGetQuizzes').click(function () {
$.getJSON("/Test/GetJsonAllQuestions/1", null, function (data) {
var div = $('#ajaxQuizzes');
div.html("<br/> " + "Quizzes received from server: " + "<br/>");
$.each(data, function (i, item) {
printQuestions(div, item);
});
});
});
});
function printQuestions(div, item) {
div.append("<br/>" + "Nazwa: " + item.Text);
}
</script>
Kod z kontrolera:
public JsonResult GetJsonAllQuizzes()
{
var lOfQuizzes = quizRepository.GetQuizzes().ToList();
return Json(lOfQuizzes, JsonRequestBehavior.AllowGet);
}
public JsonResult GetJsonAllQuestions(int id)
{
var lOfQuestions = quizRepository.GetQuizById(id).Questions;
return Json(lOfQuestions, JsonRequestBehavior.AllowGet);
}
public class Quiz
{
public int QuizId { get; set; }
public virtual ICollection<Question> Questions { get; set; }
[Display(Name = "Nazwa:")]
public string Title { get; set; }
[Display(Name = "Kategoria:")]
public string Category { get; set; }
//public int Score { get; set; }
//public DateTime? StartTime { get; set; }
//public TimeSpan? Duration { get; set; }
//public DateTime? EndTime { get; set; }
}
public class Question
{
[Display(Name = "ID")]
public int QuestionId { get; set; }
[Display(Name = "Pytanie")]
public string Text { get; set; }
[Display(Name = "Odpowiedź A:")]
public string AnswerA { get; set; }
[Display(Name = "Odpowiedź B:")]
public string AnswerB { get; set; }
[Display(Name = "Odpowiedź C:")]
public string AnswerC { get; set; }
[Display(Name = "Prawidłowa odpowiedź:")]
public string AnswerCorrect { get; set; }
[Display(Name = "Czas:")]
public int Time { get; set; }
[Display(Name = "Liczba punktów:")]
public int NumberOfPoints { get; set; }
public int QuizId { get; set; }
public virtual Quiz Quiz { get; set; }
}
}