I have been working on getting a count records within a foreach loop. I am going to need run many of these counts on a single page. I am looking for the most efficient way to do this.
I have gotten this far, but I am not sure if I headed down the right path. If I am, how do I get this data into my view.
ViewModel
public class AgtLeadStatsListVM
{
public string LoanAgent { get; set; }
public DateTime LeadDate { get; set; }
public int LeadDailyCt { get; set; }
public int LeadWeeklyCt { get; set; }
public int LeadMTDCt { get; set; }
public int LeadYTDCt { get; set; }
public IEnumerable<MWFUser> AgentList { get; set; }
public virtual WebLead Lead { get; set; }
}
Controller
var model = new AgtLeadStatsListVM();
{
// Get Selected Agent's Information
var AgentList = from l in db.MWFUsers
where (l.UserTitle == "Banker"
select l;
foreach (var agent in AgentList)
{
// Daily Lead Count
var LeadDailyCt = db.WebLeads.Count(x => (x.LoanAgent == agent.UserEmail)
&& (x.LeadDate >= todayDate && x.LeadDate <= todayEndDay));
// Weekly Lead Count
var LeadWeeklyCt = db.WebLeads.Count(x => (x.LoanAgent == agent.UserEmail)
&& x.LeadDate >= firstOfWeek
&& x.LeadDate <= todayEndDay);
// Monthly Lead Count
var LeadMTDCount = db.WebLeads.Count(x => (x.LoanAgent == agent.UserEmail)
&& x.LeadDate >= firstOfMonth
&& x.LeadDate <= todayEndDay);
// YTD Lead Count
var LeadYTDCount = db.WebLeads.Count(x => (x.LoanAgent == agent.UserEmail)
&& x.LeadDate >= firstOfMonth
&& x.LeadDate <= todayEndDay);
}
}
View
@model LoanModule.ViewModels.AgtLeadStatsListVM
<div>
@foreach (var item in Model.AgentList)
{
<p>@Model.LoanAgent</p>
<p>@Model.LeadDailyCt</p>
<p>@Model.LeadWeeklyCt</p>
<p>@Model.LeadMTDCt</p>
<p>@Model.LeadYTDCt</p>
}
I am receiving this error on my View: Object reference not set to an instance of an object. (on line: @foreach (var item in Model.AgentList))
What am I missing?
Thank you.