简体   繁体   English

对于 model 中的循环视图 ASP.NET MVC C#

[英]For loop in model view ASP.NET MVC C#

Can I use a for loop to show the model view list?我可以使用for循环来显示 model 视图列表吗? Or do I have to use foreach ?还是我必须使用foreach

If yes, can anyone show me an example please?如果是的话,谁能给我一个例子吗? Thank you.谢谢你。

@model IList<TestMVC1.Models.Account>
@{
    ViewBag.Title = "Index";
}
<h2>Accounts List</h2>
@{var student = ViewBag.AccoutList; }
@for (int i = 0; i < student.Count; i++)
{
    <div>@student[i].CounterID</div>
    <div>@student[i].AccountID</div>
    <div>@student[i].AccountName</div>
}
@foreach (var item in Model)
{
    <div>@item.CounterID</div>
    <div>@item.AccountID</div>
    <div>@item.AccountName</div>
}

I want to use it with for loop not foreach but it's not working!我想将它与for循环而不是foreach一起使用,但它不起作用! I mean the model not the viewBag我的意思是 model 不是 viewBag

@for (int i = 0; i < Model.Count ; i++)
{
    <div>@model[i].CounterID</div>
    <div>@model[i].AccountID</div>
    <div>@model[i].AccountName</div>
}

You must use the @model to define the type of model in top of view file.您必须使用@modelview文件顶部定义 model 的类型。

But if you want to access the data you should use Model or @Model .但是如果你想访问数据,你应该使用Model@Model

Change the @model to @Model@model更改为@Model

@for (int i = 0; i < Model.Count ; i++)
{
    <div>@Model[i].CounterID</div>
    <div>@Model[i].AccountID</div>
    <div>@Model[i].AccountName</div>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM