public ActionResult Survey(CustomerSurveyResponseViewModel csrv) { //create a survey object from the model provided Survey survey = new Survey() { Id = csrv.SurveyID, SurveyTitle = csrv.SurveyTitle, SurveyDescription = csrv.SurveyDesc }; /*Loop through the list of questions in the viewmodel to add the corresponding answers to the answer table*/ for (int i = 0; i < csrv.Questions.Count(); i++) { //Capture the answer value Answer answer = new Answer() { AnswerValue = csrv.Answers[i].AnswerValue, QuestionId = csrv.Questions[i].Id }; //If AnswerValue is null, don't add it if (answer.AnswerValue == null && db.Questions.Find(answer.QuestionId).Required == true) { ModelState.AddModelError(string.Empty, "Please answer all required questions!"); return(View("Survey", csrv)); } else if (answer.AnswerValue != null) { db.Answers.Add(answer); db.SaveChanges(); } //capture the SurveyResponse value CustomerSurveyResponse csr = new CustomerSurveyResponse() { SurveyId = csrv.SurveyID, SurveyName = csrv.SurveyTitle, QuestionId = csrv.Questions[i].Id, QuestionName = csrv.Questions[i].QuestionName, AnswerId = answer.Id, AnswerValue = csrv.Answers[i].AnswerValue, CustomerId = csrv.CustomerID, CreateDate = DateTime.Now }; //If AnswerValue is null, don't add it if (answer.AnswerValue != null) { db.CustomerSurveyResponses.Add(csr); } } db.SaveChanges(); return(View("Success")); }
//Get: Customers/Surveys/ID public ActionResult Survey(int?id, int?CustomerId) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } if (CustomerId == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } //create a survey object using the Find by the id parameter provided Survey survey = db.Surveys.Find(id); //create a list of questions for the questions in the db that map to the SurveyID List <Question> questions = db.Questions.Where(q => q.SurveyId == survey.Id).ToList(); Customer customer = db.Customers.Find(CustomerId); //if no survey found, return not found page if (survey == null) { return(HttpNotFound()); } if (customer == null) { return(HttpNotFound()); } //create the view model object to return to the view CustomerSurveyResponseViewModel csrv = new CustomerSurveyResponseViewModel() { SurveyID = survey.Id, SurveyTitle = survey.SurveyTitle, SurveyDesc = survey.SurveyDescription, Questions = questions, CustomerID = customer.Id }; return(View(csrv)); }