如何在没有foreach或for循环的mvc 5视图中迭代IEnumerable

时间:2017-06-02 18:49:55

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

我正在创建问卷调查应用程序,我必须加载随机问题并从用户那里获得答案。 我想知道,我应该如何使用按钮迭代记录。 我知道如何在视图上使用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>

1 个答案:

答案 0 :(得分:0)

以下是基本大纲:https://dotnetfiddle.net/xKdwlK

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

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

相关问题