MVC4 Survey Web App的结构 [英] Structure for MVC4 Survey Web App
问题描述
我正在尝试使用MVC架构找出调查应用程序的模型结构.实际上,这是较大的WebApp中的问答"部分.我大约有120个问题,他们都会为答案设定选项,没有书面答案.目前我有3张桌子:
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)
因为有120个.我需要使用循环之类的东西吗?我也不想将问题硬编码到应用程序中,因为将来在应用程序上线时我可能会添加/删除/编辑问题.
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.
我进行了搜索,但只找到用于创建调查的应用程序,而不是在MVC中构建的实际调查.如果您知道任何示例,请告诉我.
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.
推荐答案
我实际上在本周早些时候遇到了同样的问题.我最终成功完成的工作是:
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; }
我的视图在foreach块中使用DropDownList而不是DropDownListFor,并且我使用每个问题的ID来设置名称:
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>
}
在Controller上的HttpPost上,我将FormCollection作为参数传递给Action,然后再次遍历结果集.这似乎效率低下,但在多种情况下进行了测试,并且运行速度非常快.
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)];
}
}
这篇关于MVC4 Survey Web App的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!