首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >错误: asp.net MVC-5模型项到IEnumerable

错误: asp.net MVC-5模型项到IEnumerable
EN

Stack Overflow用户
提问于 2019-11-19 07:07:52
回答 1查看 197关注 0票数 1

我正在使用.NET MVC-5。我得到了上面的错误。在我的例子中,我有一个名为“客户控制器”的控制器。它由两个操作结果组成,命名为“索引”“Details”。

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

客户控制器

代码语言:javascript
复制
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

代码语言:javascript
复制
<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

代码语言:javascript
复制
<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>

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-19 07:33:19

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

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

1)这里的,您将得到没有foreach的对象值,如下所示。

代码语言:javascript
复制
<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对象。

代码语言:javascript
复制
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);

}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58928395

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档