问题
I am trying to figure out the model structure for a survey app, using the MVC architecture. Actually it is a Q&A section within a larger WebApp. I have about 120 questions and they will all have set options for answers, no written answers. Currently I have 3 tables:
Question(id, QuestionText)
Answer(id, Userid, Questionid, AnswerOptionId)
AnswerOption(id, Option) - example: Yes, No, 1-10, etc
I am trying to figure out how to build my viewmodel and view. I can't just have something like:
@Html.LabelFor(m => m.QuestionText)
because there are 120 of them. Do I need to use a loop or something? I also don't want to hard code the questions into the app, because I will likely add/remove/edit questions in the future when the app is live.
I did a search but only found apps for creating surveys, not an actual survey built in MVC. Let me know if you know of any examples.
回答1:
I actually ran in to this same problem earlier this week. What I ended up doing, successfully, was this:
My Model consists of a list of Questions, which is a custom class I wrote with the necessary properties needed for my scenario:
List<Question> Questions { get; set; }
My View uses a DropDownList inside of a foreach block as opposed to a DropDownListFor, and I am setting the name using the Id of each question:
@foreach (Question question in Model.Questions)
{
<li>@question.QuestionText</li>
<li>Answer: @Html.DropDownList(String.Format("ddlAnswer{0}", question.QuestionId), Model.Answers)</li>
}
On HttpPost on the Controller, I am passing in the FormCollection as a parameter to the Action and am again iterating through the results set. This would appear to be inefficient but tested in multiple scenarios it runs very quickly.
[HttpPost]
public ActionResult Index(SurveyModel model, FormCollection form)
{
foreach (Question question in model.Questions)
{
question.QuestionAnswer = form[String.Format("ddlAnswer{0}", question.QuestionId)];
}
}
来源:https://stackoverflow.com/questions/17633929/structure-for-mvc4-survey-web-app