HTML and CSS Reference
In-Depth Information
Table 7-4.
Keys Used in the JSON Dictionary
Key
Value
FirstName
A string value indicating the user's first name
LastName
A string value indicating the user's last name
Email
A string indicating the user's e-mail address
<choice_id>
<question_id>
An integer indicating the
QuestionID
of the choice: for example,
localStorage["3"] = 1
where 3 is a
ChoiceID
and 1 is a
QuestionID
Note that
localStorage
is a key-value collection, and each key needs to be unique. Each choice in the
Choices
table has a unique
ChoiceID
. That is why you make
ChoiceID
the key and
QuestionID
the value. If
you did it the other way around, you couldn't store multiple choices for a question—the latest
ChoiceID
would overwrite the previously stored
ChoiceID
because the
QuestionID
for both would be the same.
Once
SaveResults()
returns successfully, all the data from
localStorage
is removed using the
clear()
method. The
SaveResults()
action method that saves the survey results in the
Results
table is shown in
Listing 7-13.
Listing 7-13.
SaveResults()
Action Method
public JsonResult SaveResults()
{
string jsonData = string.Empty;
using (StreamReader sr = new StreamReader(Request.InputStream))
{
jsonData = sr.ReadToEnd();
}
Dictionary<string, string> data =
JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonData);
SurveyDbEntities db = new SurveyDbEntities();
User usr = new User();
usr.FirstName = data["FirstName"];
usr.LastName = data["LastName"];
usr.Email = data["Email"];
db.Users.AddObject(usr);
db.SaveChanges();
string userEmail = data["Email"];
int usrId = (from item in db.Users
where item.Email == userEmail
select item.UserID).SingleOrDefault();
data.Remove("FirstName");
data.Remove("LastName");
data.Remove("Email");
foreach (string str in data.Keys)
{
int choiceId = int.Parse(str);