【问题标题】:razor MVC foreach with @using (html.beginform())razor MVC foreach 与 @using (html.beginform())
【发布时间】:2015-01-27 23:24:01
【问题描述】:

我需要创建一个带有问题和文本框的表单,以允许用户输入他们的答案并发送以进行验证。似乎@using (Html.BeginForm())@foreach 无效。下面是代码,但我不确定这是否是正确的方法。有人可以指出我正确的方向吗?或者我如何在场景中使用@using (Html.BeginForm())

@model PairingTest.Web.Models.QuestionnaireViewModel

<html>
<head>
    <title>@Model.QuestionnaireTitle</title>
</head>
<body>
    <form action="~/Questionnaire/ProcessData" method="post">

        @foreach (var s in Model.QuestionsText) {

            <text> Question :</text>@s <br />
            @Html.Label("Ans");<br />
            @Html.TextBox("Ans");<br /> 

        }

        <button type="submit">Submit</button>
    </form> 
</body>

【问题讨论】:

  • 你能用你的剃刀表单而不是html表单显示代码
  • 顺便说一句,我对您的问题的猜测是您在 using (HTML.beginform()) 和 foreach 前面都有 @ 符号。实际上,当它在 using (HTML.beginform()) 中被包围时,您实际上不需要 for each 的 @ infront,因为它在剃刀范围内,并且会抛出错误。
  • 您发回的控制器方法签名是什么,模型是什么?你在这里所做的只是发布一个包含Ans 值的数组,这些值没有绑定到任何东西,而且毫无意义

标签: c# asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 razor


【解决方案1】:
@using(Html.BeginForm())
{
  for(int i=0;i< Model.QuestionsText.Count;i++)
  {
     <text> Question :</text>@s <br />
     @Html.Label("Ans");<br />
     @Html.TextBoxFor(m => Model.QuestionsText[i].Ans);
  }
}

这将发布 QuestionsText 集合,如果您有任何疑问,请告诉我。

【讨论】:

    【解决方案2】:

    您需要将 IEnumerable 与模型一起使用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-12
      • 2011-07-09
      • 2016-07-28
      • 1970-01-01
      • 2014-06-18
      • 1970-01-01
      相关资源
      最近更新 更多