首页 > 解决方案 > asp.net mvc中的转发器foreach

问题描述

我正在使用 MVC 在 ASP.Net 中构建一个网站,需要列出一组结果,但代码中出现错误

模型:

public class Customers
{
  public int Id { get; set; }
  public string Name { get; set; }
  public List<Customers> Itemlst { get; set; }
} 

控制器:


    public ActionResult List()
{
     Customers itemobj = new Customers();

     return View(itemobj);
}   

看法:


@foreach(var item in Model.Itemlst)
{
     <tr>
          <td>Items ID:</td>
          <td>@item.ID</td>
          <td>Items Name:</td>
          <td>@item.Name</td>
     </tr>
}

</table>

标签: asp.net-mvc

解决方案


NullReferenceException您收到的消息中,我们可以看到问题是由于Itemlst未初始化。解决此问题的方法之一就是确保在创建对象时存在有效列表:

public class Customers
{
    public Customers()
    {
      Itemlst = new List<Customers>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public List<Customers> Itemlst { get; set; }
} 

因此,如果需要,您可以在操作中将值添加到列表中:

public ActionResult List()
{
     Customers itemobj = new Customers();

     var example = new Customers ();
     example.Id = 1;
     example.Name = "Example";

     itemobj.Add();
     return View(itemobj);
}  

我不知道您是否只是将此作为您问题的示例,但我不禁注意到有些奇怪。您可以使用不同的东西,例如:

public class ViewModel // Name to what makes sense to you
{
    // Some other properties...

    public List<Customer> Customers { get; set; }
} 

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
} 

或者您可以List<Customer>直接在视图中用作模型(是的,您的模型可以是一个简单的对象列表的对象)。


推荐阅读