【问题标题】:ASP.Net MVC Submit Post Data for SurveyASP.Net MVC 提交调查后数据
【发布时间】:2010-09-10 04:50:50
【问题描述】:

当我为收集调查答案的表单提交时,我很难弄清楚如何从 FormCollection 中收集数据。具体来说,我的问题是具有多项选择选项(单选按钮)和其他文本框字段(如果选项不适用)的问题。

我的调查具有以下结构:

QUESTION : [ QuestionId, Text, QuestionType, OrderIndex]

MULTIPLE_CHOICE_OPTIONS:[MC_OptionId, QuestionId, OrderIndex, MC_Text]

ANSWER: [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 值。

有没有更好的方法来解决这个问题,无论是数据库结构、视图渲染代码还是表单控件的命名方式?也许表单收集不是要走的路,但我很难过如何回发并使模型绑定工作。

感谢您的帮助,一直在兜圈子寻找看起来很简单的东西。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-2 forms postback survey


    【解决方案1】:

    考虑一下这个小重构...

    //you're always rendering the radios, it seems?
    RenderPartial("MultipleChoice", Model.MULTIPLE_CHOICE_OPTIONS.Where(x => 
                                       x.QuestionId == q.QuestionId));
    
    if (q.QuestionType == Multiple_Choice_wOtherOption)
    {   
       <textbox name="Other|" + q.QuestionId />      
    }
    

    在强类型部分视图中:

    //Model is IEnumerable<MultipleChoice_Option >
    foreach (MultipleChoice_Option mc in Model ) 
    {
        <radio name=mc.Question.QuestionId value=mc.MC_OptionId />           
    }
    

    您的问题似乎与文本框名称有关;通过 ID 与问题相关联。在您的控制器中,您必须明确知道何时在文本框中查找任何值。

     string userAnswer = Request.Form["OtherEntry|" + someQuestionID].ToString();
    

    【讨论】:

      猜你喜欢
      • 2012-05-05
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多