0

我正在尝试使用 MVC 架构找出调查应用程序的模型结构。实际上它是一个更大的 WebApp 中的问答部分。我有大约 120 个问题,他们都有设置的答案选项,没有书面答案。目前我有3张桌子:

Question(id, QuestionText)
Answer(id, Userid, Questionid, AnswerOptionId)
AnswerOption(id, Option) - example: Yes, No, 1-10, etc

我想弄清楚如何构建我的视图模型和视图。我不能只有这样的东西:

@Html.LabelFor(m => m.QuestionText)

因为有120个。我需要使用循环或其他东西吗?我也不想将问题硬编码到应用程序中,因为将来当应用程序上线时,我可能会添加/删除/编辑问题。

我进行了搜索,但只找到了用于创建调查的应用程序,而不是 MVC 中内置的实际调查。如果您知道任何示例,请告诉我。

4

1 回答 1

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)];
     }
}
于 2013-09-11T11:58:29.427 回答