当我为收集调查答案的表单提交表单时,我很难弄清楚如何从 FormCollection 收集数据。具体来说,我的问题是具有多项选择选项(单选按钮)和其他文本框字段(如果选项不适用)的问题。
我的调查具有以下结构:
QUESTION : [ QuestionId, Text, QuestionType, OrderIndex]
MULTIPLE_CHOICE_OPTIONS:[MC_OptionId,QuestionId,OrderIndex,MC_Text]
答案:[AnswerId,QuestionId,MC_OptionId(可以为空),UserTextAnswer]
QUESTION_TYPES 是:[Multiple_Choice、Multiple_Choice_wOtherOption、FreeText 或 Checkbox]
我的观点是呈现如下形式(伪代码简化):
//Html.BeginForm
foreach( Question q in Model.Questions)
{
q.Text //display question text in html
if (q.QuestionType == Multiple_Choice)
{
foreach( MultipleChoice_Option mc in Model.MULTIPLE_CHOICE_OPTIONS(opt => opt.QuestionId == q.QuestionId)
{
<radio name=q.QuestionId value=mc.MC_OptionId />
// All OK, can use the FormCollectionKey to get the
// QuestionId and its value to get the selected MCOptionId
}
}
else if (q.QuestionType == Multiple_Choice_wOtherOption)
{
foreach( MultipleChoice_Option mc in Model.MULTIPLE_CHOICE_OPTIONS(opt => opt.QuestionId == q.QuestionId)
{
<radio name=q.QuestionId value=mc.MC_OptionId />
}
<textbox name=q.QuestionId />
// ****Problem - I can get the QuestionId from the FormCollection Key, but
// I don't know if the value is from the user entered
// textbox or from a MCOptionId***
}
}
<button type="submit">Submit Survey</button>
// Html.EndForm
我是这样做的,所以回到处理回发的控制器操作中,我可以通过键读取 FormCollection 以获取 questionId,以及每个索引的值以获取 MCOptionID。但是对于单选按钮和文本框都具有相同名称键的问题,我将如何确定表单数据是来自单选按钮还是文本框。
我可以看到我这样做的方式会中断,因为它们可能是问题(id = 1)有一个MCOption w / Id = 5的情况,因此单选按钮的值为5并且用户在其他文本框中输入5 . 当表单提交时,我看到 formcollection[key="1"] 的值为 5,我无法判断这是来自 usertext 还是来自引用 MCOptionId 的 radioButton 值。
有没有更好的方法来解决这个问题,无论是数据库结构、视图渲染代码还是表单控件的命名方式?也许表单收集不是要走的路,但我很难过如何回发并使模型绑定工作。
感谢您的帮助,一直在寻找一些看起来很简单的东西。