如何在MVC5实体框架中显示foreach语句中的项目

时间:2017-11-29 11:31:34

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

我在控制器和视图中有一个索引。 当我在文本框搜索中输入学生ID时,我想显示学生的信息并列出他们的所有活动。怎么做。 非常感谢你!

控制器:

public ActionResult Index(string Sid)
{
    var grad = db.Gradings.Include(g => g.Activity).Include(g => g.Student).Where(g => g.StudentID == Sid).ToList();      
}

查看:

<div class="col-xs-4">
    <p>
        @using (Html.BeginForm())
        {
            <p>
                Student ID: @Html.TextBox("Sid",ViewBag.FilterValue as string)
                <input type="submit" value="Search" />
            </p>
        }
        <table class="table">
            <tr>
                <th>Activity Name</th>
                ....
            </tr>
            @foreach (var item in Model)
            {   
                <tr>
                    <td>@Html.DisplayFor(modelItem => item.Activity.Name)</td>
                    <td>@Html.DisplayFor(modelItem => item.Responsibility)</td>
                    ....
                </tr>
            }
        </table>
    </div>
    <h3> Total score: @ViewBag.Total</h3>

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

当用户请求时,您最初需要一个操作来提供视图:

public ActionResult Index()
{
    return View();     
}

然后,当请求提交表单时,您需要另一个操作来处​​理用户的请求:

public ActionResult Index(string Sid)
{
    var grad = db.Gradings.Include(g => g.Activity).Include(g => g.Student).Where(g => g.StudentID == Sid).ToList();  

    return View(grad);    
}

现在gradList<Grading>,我们将其作为模型传递给视图,因此请确保在视图中使用它。您可能需要包含ListGrading的命名空间:

@model List<Grading>

最后,不要在视图中使用foreach,而是使用for循环,以便HTML标记具有唯一ID。现在(使用foreach),所有Grading条记录都具有相同的名称和id属性。