如何使用razor在html中迭代列表变量

问题描述 投票:1回答:4

我是asp .net和MVC的新手。我有一个名为Jumbo()的服务方法。此方法返回包含名字,姓氏和联系号码的列表。我从我的主项目中调用这个方法,如下所示。我也将它返回到视图页面。

var info = add.jumbo();
ViewData["sample"] = info;

return View("FormResults");

当我调试代码时,变量'info'包含我需要的所有数据。问题是如何使用razor在html表中迭代变量。我搜索了很多寻找解决方案,但我失败了。请帮我解决一下。提前致谢。

c# asp.net html5 asp.net-mvc-4 razor
4个回答
3
投票

案例1:基本上您可以在应用程序本身中观察到这一点。 MVC本身为您提供答案。什么时候 ?当您针对返回列表的操作创建View时。说你的行动返回客户列表然后你可以观察下面的代码。

@model IEnumerable<Customer>

<h2>Customers</h2>
<p>
    @Html.ActionLink("Create New", "CreateCustomer", "ControllerName")
</p>
<table>
    <tr>

        <th>
            @Html.DisplayNameFor(model => model.Email)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {    
        <tr>           
            <td>
                @Html.DisplayFor(modelItem => item.Email)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>

                <td>                        

                    @Html.ActionLink("Edit |", "UpdateCustomer", new { id =  item.Id}) 
                    @Html.ActionLink("Details", "Details", new { id =  item.Id}) 
                    @Html.ActionLink("Delete", "Delete", new { id =  item.Id})                      
               </td>           
        </tr>
    }
</table>

案例2:您的方案是在ViewData中发送列表时。然后,您必须将ViewData转换为相应的模型列表,然后您可以执行相同的foreach循环。行动:var info = add.jumbo(); ViewData [“sample”] = info;

return View("FormResults");

视图:

  @if (ViewData["sample"] != null)
    {
        List<Info> infoList = (List<Info>)ViewData["sample"];
        foreach (var i in infoList)
        { 
        //Perform your html here enclosed with html tags.
        }        
    }

5
投票

首先,您需要将模型传递给视图:

return View("FormResults", info);

在视图中,您需要声明模型的类型,并使用@来表示代码而不是html:

@model List<Foo> // Whatever your list is
@foreach (var item in Model)
{
    <span>@item.Text</span>
}

这是一篇关于它的博客:http://weblogs.asp.net/scottgu/asp-net-mvc-3-new-model-directive-support-in-razor


2
投票

在您的视图中编写一个foreach循环,如下所示

@model List<Object>
@foreach(var item in Model)
{
  item.YourProperty;//without html
  <label>@item.YourProperty</label> //in html
}

1
投票
@model  Models.Nodes 
@foreach (var item in Model)
{
 <li>
    <span> item.name </span>
 </li>
}
© www.soinside.com 2019 - 2024. All rights reserved.