c# - 如何在没有 foreach 或 for 循环的情况下在 mvc 5 View 中迭代 IEnumerable

标签 c# entity-framework asp.net-mvc-5

我正在创建问卷调查应用程序,我必须在其中加载随机问题并从用户那里获得答案。 我想知道,我应该如何使用按钮迭代记录。 我知道如何在 View 上使用 foreach/for 循环显示数据,但要求是我必须一次显示一个问题,得到答案,将其存储在列表中,当用户按下“下一步”按钮时,我必须向用户呈现下一个问题记录。 我将不胜感激在这方面的任何帮助。 谢谢。 我在这里附上了我的示例代码:

查看模型类:

public class ExamViewModel
{
    public IEnumerable<Question> QuestionsList { get; set; }
    public string Heading { get; set; }

    public Question GetQuestionAtIndex(IEnumerable<Question> questionsList, int index = 0)
    {
        return questionsList.ElementAt(index);
    }
}

查看:

<h2>@Model.Heading</h2>
<div class="panel-body">
        @{
            int index = 0;
            var question = Model.GetQuestionAtIndex(Model.QuestionsList, index);
        }
        <div class="form-group">
            <div class="col-sm-8">
                <ul class="list-group">
                    <li class="list-group-item list-group-item-heading list-group-item-warning">
                        @question.QuestionText
                    </li>
                </ul>
            </div>
        </div>
</div>

最佳答案

这是一个基本大纲:https://dotnetfiddle.net/xKdwlK

在那个例子中,我只是将所有答案加载到一个数组中,然后使用 ajax 将其发送到 Controller 。我没有编写 Controller 保存方法,因为我不知道你在那里需要什么,但你可以填写它。

这只是一种方法,但您也可以使用表单提交而不是 ajax。

关于c# - 如何在没有 foreach 或 for 循环的情况下在 mvc 5 View 中迭代 IEnumerable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44335625/

相关文章:

authentication - Owin和Windows身份验证(mvc5)-使用Windows身份验证作为登录的一部分

c# - 如何将包含十六进制字符的字符串转换为字符串

C# - 使用 session 存储变量的副本而不是引用

c# - 如何以编程方式获取特定服务器标识

c# - 无法访问 User.Identity 中的声明,但可以在断点 View 中查看它们

entity-framework - 存储库模式 : Deleting the aggregate root

c# - 显示组合框中外键约束的名称

entity-framework - 使用 Attach 方法时 EF 6 OriginalValues 丢失

sql-server - SQL哈希密码

asp.net-mvc - 如何检查经过身份验证的用户是常规 ASP.NET Identity 帐户还是链接到外部提供商的帐户