HTML and CSS Reference
In-Depth Information
Listing 7-8.
GetQuestions()
Action Method
public JsonResult GetQuestions()
{
SurveyDbEntities db = new SurveyDbEntities();
var data = from item in db.Questions
select item;
return Json(data.ToArray());
}
The
GetQuestions()
action method selects all the question items from the
Questions
table and returns
them as an array. Because the return value is to be accessed in jQuery code, it's converted into JSON format
using the
Json()
method and then returned as a
JsonResult
.
Notice the use of
data-*
attributes in Listing 7-7. As discussed in Chapter 6, the
data-*
attributes are
different than standard HTML attributes in that they're developer defined and don't directly affect the
element in any way. All
data-*
attributes begin with prefix
data-
followed by a developer-defined attribute
name. An element can have any number of
data-*
attributes, which you can access programmatically
using jQuery code.
The dynamically generated
<div>
element defines one
data-*
attribute named
data-questions-
questionid
. This attribute stores the
QuestionID
of a question from the
Questions
table. A sample
dynamically generated
<div>
element looks like this:
<div data-questions-questionid='1'>Which programming language do you use?</div>
The
success
handler function then calls the
GetChoices()
function to populate choices for each of the
questions. The
GetChoices()
function is shown in Listing 7-9.
Listing 7-9.
GetChoices()
Client-Side Function
function GetChoices() {
$.ajax({
type: "POST",
url: "/Home/GetChoices",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(results){
for (var i = 0; i < results.length; i++) {
$("div[data-questions-questionid='" + results[i].QuestionID + "']").append(
"<br /><input type='checkbox' data-choices-questionid='" +
results[i].QuestionID +
"' data-choices-choiceid='" + results[i].ChoiceID +
"'/><span>" + results[i].ChoiceText + "</span>");
if (storage[results[i].ChoiceID] != null) {
var choiceId = results[i].ChoiceID;
$("input[data-choices-choiceid='" +
choiceId + "']").attr('checked', 'checked');
}
}
$("input[data-choices-questionid]").change(function (event) {
var key = $(event.target).attr("data-choices-choiceid");
if ($(event.target).is(':checked') == true) {
storage[key] = $(event.target).attr("data-choices-questionid");
}
else {