可以在ASP.NET MVC 5中使用IEnumerable

时间:2014-03-09 00:38:49

标签: c# asp.net asp.net-mvc asp.net-mvc-5

这是我的代码:

CONTROLLER:

    public async Task<ActionResult> Index()
    {
        if(User.IsInRole("admin")){
            return View(await db.Customers.ToListAsync());
        }
        else if(User.IsInRole("employee"))
        {
            var list = from c in db.Customers
                       where c.User.Id == User.Identity.GetUserId()
                       select c;
            var e = list.AsEnumerable();                
            return View(e);


            //tried this too : 
            //var list = db.Customers.Where(c=>c.User == User); 
            //return View(list);

        }
        return RedirectToAction("Error");
    }

查看:

@model IEnumerable<AspnetIdentitySample.Models.ApplicationUser>

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.UserName)
        </th>
    </tr>

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

            </td>

        </tr>
    }

</table>

为什么我无法在视图中显示查询结果?任何帮助,将不胜感激! :)谢谢。

1 个答案:

答案 0 :(得分:4)

这是由于名为延迟执行的东西。您正在返回IQueryable实例..但此实例不包含您想要的数据。它包含一个执行计划,可用于查询结果。

您需要强制评估查询。执行此操作的一般方法是调用ToList()(请注意,您已在if语句的其他逻辑分支上执行此操作:

return View(list.ToList());

您的问题(以及它编译的原因)是因为IQueryable实现了IEnumerable。所以把它传递到你的视图是好的。 IList也会实施IEnumerable ..因此ToList()强制评估您的IQueryable,并且仍然可以传递给视图。

视图中也存在此问题(foreach循环之外):

@Html.DisplayNameFor(model => model.UserName)

您的模型是一个集合..所以这不起作用,因为IEnumerable<T>没有UserName属性(但它的项目有)。

相关问题