0

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. 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. Or do I need to create a model for these results?

JOb801
  • 5
  • 1
  • 5

1 Answers1

0

With new { Domain = g.Key, Count = g.Count() } you are creating new anonymous type. 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.

nejcs
  • 1,212
  • 10
  • 14