简体   繁体   English

在局部视图中声明通用IEnumerable

[英]Declare Generic IEnumerable in Partial View

Pretty sure this has been answered before and I'm just not using the correct verbiage when I search... 可以肯定的是,这已经得到了回答,并且在搜索时我没有使用正确的字词...

I'm new to MVC and C#, trying to map the results of a LINQ query to a partial view and I don't know how to declare the view model so I can loop through the results. 我是MVC和C#的新手,试图将LINQ查询的结果映射到部分视图,但我不知道如何声明视图模型,因此无法遍历结果。 I am not mapping these results to a model. 我没有将这些结果映射到模型。 I'm just trying to get some stats from a table, and it doesn't seem justified to create a class for this simple query... or is it? 我只是想从表中获取一些统计信息,为这种简单的查询创建类似乎没有道理……还是吗?

Controller 控制者

        public ActionResult _DomainCounts()
    {
        DB.Log = Console.Out;
        var totals = from p in DB.Redirects
                 group p by p.Domain into g
                 select new
                 {
                     Domain = g.Key,
                     Count = g.Count()
                 };

        return PartialView("_DomainCounts", totals.AsEnumerable());
    }

View 视图

@model IEnumerable

@foreach (var d in Model)
{
     @d.Domain, @d.Count <br />
}

Obviously my View doesn't know what Domain and Count are, and I don't know how to declare it properly. 显然,我的View不知道Domain和Count是什么,也不知道如何正确声明它。 Or do I need to create a model for these results? 还是我需要为这些结果创建模型?

With new { Domain = g.Key, Count = g.Count() } you are creating new anonymous type . 使用new { Domain = g.Key, Count = g.Count() }您将创建新的匿名类型 You are basically saying: I don't care what the class name is, I just want it to have those two properties. 您基本上是在说:我不在乎类名是什么,我只希望它具有这两个属性。 But in your case you do care what the name is since otherwise you cannot declare what the type of model is. 但是在您的情况下,您确实关心名称是什么,因为否则您将无法声明模型的类型。 So as other have mentioned, you will have to explicitly create class with those two properties, use it as result of query and then you can declare correct type of your model. 因此,正如其他人提到的那样,您将必须使用这两个属性显式创建类,将其用作查询结果,然后可以声明模型的正确类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM