首页 > 解决方案 > 错误:asp.net MVC-5 模型项到 IEnumerable

问题描述

我正在使用 .NET MVC-5。我得到了上述错误。就我而言,我有一个名为“客户控制器”的控制器。其中包括两个名为“索引”“详细信息”的操作结果。

索引正在从数据库中呈现客户列表。问题是如果我点击客户列表中的任何名称(由“索引”呈现)应该将我重定向到详细信息操作结果并显示与特定客户相关的详细信息。

客户控制器

public class CustomerController : Controller
{
    private ApplicationDbContext _context;

    public CustomerController()
    {
        _context = new ApplicationDbContext();
    }

    protected override void Dispose(bool disposing)
    {
        _context.Dispose();

    }
    // GET: Customer
    public ActionResult Index()
    {
        var customers = _context.Customers.ToList();
        return View(customers);
    }

    public ActionResult Details(int  id)
    {
        var cus = _context.Customers.FirstOrDefault(c=> c.Id==id);
        if (cus == null)
            return  HttpNotFound();
        return View(cus);

    }
}

索引 cshtml

<table class="table table-bordered table-responsive table-hover">
<thead>
<tr>
    <th>Customer Name</th>
</tr>
</thead>
<tbody>

@foreach (var i in Model)
{
    <tr>

        <td>@Html.ActionLink(@i.Name, "Details", "Customer", new {id=1 }, null)</td>
    </tr>
}

</tbody>

详细cshtml

<table class="table table-bordered table-hover table-responsive">
<thead>
<tr>
    <th>Customer Id</th>
    <th>Customer Name</th>
</tr>
</thead>
<tbody>

@foreach (var i in Model)
{ 
    <tr>
        <td> @i.Id @i.Name </td>
    </tr>
}


</tbody>

标签: .netasp.net-mvcasp.net-mvc-5

解决方案


您正在使用 选择数据FirstOrDefault,因此它将返回Customers类的单个实体对象,并且您正在尝试对其进行迭代,这是错误的。

在这里,您可以使用2 种方式解决它。

1)在这里你会得到对象值,而foreach不像下面这样。

<table class="table table-bordered table-hover table-responsive">
<thead>
<tr>
    <th>Customer Id</th>
    <th>Customer Name</th>
</tr>
</thead>
<tbody>

    <tr>
        <td> @i.Id @i.Name </td>
    </tr>

</tbody>

2)如果您不想更改视图代码,那么您需要list从控制器传递对象,如下所示。

public ActionResult Details(int  id)
{
   var cus = _context.Customers.FirstOrDefault(c=> c.Id==id);
   List<Customers> lstcus =  new List<Customers>();
   lstcus.Add(cus);

   if (cus == null)
        return  HttpNotFound();

   return View(lstcus);

}

推荐阅读