I have an application to create and edit surveys. Each survey contains a set of questions and associated responses (answers). When a survey is created, the collection of questions is generated from a separate Questions
table. Each year, a new survey is created for each user with the same set of questions so that responses can be compared over time.
When a survey is created, the answers to each question are saved, but a user may not have given a response to each question and now I have to build an view to edit existing responses.
Models
public class Survey
{
public int ID { get; set; }
public int AreaID { get; set; }
public Status Status { get; set; }
public DateTime AssessmentDate { get; set; }
public virtual Area Area { get; set; }
public virtual ICollection<Answer> Answers { get; set; }
}
public class Question
{
public int ID { get; set; }
public string QuestionText { get; set; }
public virtual ICollection<Answer> Answers { get; set; }
}
public class Answer
{
public int ID { get; set; }
public int? Response { get; set; }
public int QuestionID { get; set; }
public int SurveyID { get; set; }
public virtual Question Question { get; set; }
public virtual Survey Survey{ get; set; }
}
Here is my viewmodel that I use to create my view for the edit screen
public class SurveyResponseViewModel
{
public Assessment Assessment { get; set; }
public IEnumerable<Question> Questions { get; set; }
}
and the code in the GET method is
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Survey survey = db.Surveys.Find(id);
var viewModel = new SurveyResponseViewModel
{
Survey = survey,
Areas = new SelectList(db.Areas, "ID", "SubLevel").ToList(),
Questions = db.Questions.Where(q => q.isActive)
};
if (survey == null)
{
return HttpNotFound();
}
return View(viewModel);
}
This populates my view model with all questions, but each question contains a collection of answers. How do I display and edit only the answer to each question associated with this survey in the view?
@foreach (var question in Model.Questions)
{
// Display the question
@Html.Raw(question.QuestionText)
// How to create an input for the associated response??
<input type="text" name="????" placeholder="Enter a number..." value="????" />
}
Note that the response is int?
and can have a value between 0
and 5
(or null
if the user has not yet given the response). Ideally I would like this to be rendered as a radio buttons to select the possible values.