HTML and CSS Reference
In-Depth Information
error: function (err) {
alert(err.status + " - " + err.statusText);
The GetChoices() function invokes the GetChoices() action method using the $.ajax() method. The
GetChoices() action method returns an array of choice items. The success handler function iterates
through all the choice items returned, and with each iteration, a choice is added to a question by
dynamically generating a check box. You need to append all the choices belonging to a question inside
that question's <div> element. Notice the jQuery selector that selects a <div> with data-questions-
questionid attribute equal to the QuestionID . This way, the check boxes for choices are added to the <div>
showing their question. Also notice how the code sets the data-choices-questionid and data-choices-
choiceid attributes of the <input> element for later use. These two attributes represent the QuestionID and
ChoiceID of a choice, respectively. A sample <div> with check boxes added looks like this:
<div data-questions-questionid='1'>Which programming language do you use?<br />
<input type='checkbox' data-choices-questionid='1' data-choices-choiceid='1'/>
<input type='checkbox' data-choices-questionid='1' data-choices-choiceid='2'/>
<input type='checkbox' data-choices-questionid='1' data-choices-choiceid='3'/>
After you add the check boxes, you determine their checked status from localStorage , and
accordingly they're checked or kept unchecked. If a user toggles the choice selection, you need to
synchronize localStorage with the new selection. You do this in the change event handler of the
dynamically added check boxes. The change event handler essentially determines whether a check box is
checked ( :checked selector), and an entry is added to or removed from the localStorage . When you add an
item in localStorage , a ChoiceID acts as a key and its QuestionID acts as a value.
The GetChoices() action method used by the GetChoices() function discussed earlier is shown in
Listing 7-10.
Listing 7-10. GetChoices() Method
public JsonResult GetChoices()
SurveyDbEntities db = new SurveyDbEntities();
var data = from item in db.Choices
select item;
return Json(data.ToArray());
The GetChoices() method is similar to the GetQuestions() method but returns all the choices from the
Choices table.
When a user fills out the survey form and clicks the Submit Answers button, the SubmitData() function
is called. This function in turn calls the SaveResults() action method using the jQuery $.ajax() method.
The code in Listing 7-11 shows how this is done.
Search WWH ::

Custom Search