在 for 循环剃刀视图中分组

Phi*_*ers 2 c# asp.net-mvc razor

我的剃刀视图中有以下内容

                @foreach (var group in Model.QuestionList.GroupBy(x => x.AreaName))
            {
                <h4>@group.Key</h4>

                for (int i = 0; i < Model.QuestionList.Count(x => x.AreaName == group.Key); i++)
                {

                <div class="form-group">
                    <div class="row">
                        <div class="col-md-4">
                            @Html.DisplayFor(x => Model.QuestionList[i].Question)
                        </div>
                        <div class="col-md-2">
                            @Html.HiddenFor(x => Model.QuestionList[i].StnAssureQuestionId)
                            @Html.DropDownListFor(model => model.QuestionList[i].Score, new SelectList(Model.QuestionList[i].Scores, "ScoreId", "ScoreNum", 0), "Please Select", new { @class = "form-control" })
                            @Html.ValidationMessageFor(model => model.QuestionList[i].Score, "", new { @class = "text-danger" })
                        </div>
                        <div class="col-md-4">
                            @Html.EditorFor(x => Model.QuestionList[i].Comments, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.QuestionList[i].Comments, "", new { @class = "text-danger" })
                        </div>
                    </div>
                </div>
                }
            }
Run Code Online (Sandbox Code Playgroud)

我希望能够显示 QuestionList 中的所有对象,但按 AreaName(组键)对它们进行分组。

当前代码显示第一组的标题,然后显示该组中的问题,但之后它所做的只是显示下一个组名称,后跟相同的问题,然后再次显示所有组。

我确信这是理所当然的,但我仍然不够熟练来发现它。

Jam*_*D77 6

您也许可以解决这样的问题,但我也会听取其他人关于为此视图创建特定视图模型的建议。

@foreach (var group in Model.QuestionList.GroupBy(x => x.AreaName))
{
    var questionList = group.ToList();
    <h4>@group.Key</h4>
    for (int i = 0; i < questionList.Count(); i++)
    {
        <div class="form-group">
            <div class="row">
                <div class="col-md-4">
                    @Html.DisplayFor(x => questionList[i].Question)
                </div>
                <div class="col-md-2">
                    @Html.HiddenFor(x => questionList[i].StnAssureQuestionId)
                    @Html.DropDownListFor(model => questionList[i].Score, new SelectList(questionList[i].Scores, "ScoreId", "ScoreNum", questionList[i].Score), "Please Select", new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => questionList[i].Score, "", new { @class = "text-danger" })
                </div>
                <div class="col-md-4">
                    @Html.EditorFor(x => questionList[i].Comments, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => questionList[i].Comments, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>
    }
}            
Run Code Online (Sandbox Code Playgroud)

点网小提琴示例