Inkey
Inkey

Reputation: 2207

IEnumerable MVC Controller to View

I am trying to pass a var from a controller and access the information inside a view.

Inside the controller i have the following LINQ statement that totals up a sum of some columns that i need. I have in the past just passed the var to a list and then passed the list across.

The problem is that i am unsure as to how i pass this var across.

The following is the Controller code

    var GoodProduct =
new
{
    CastGoodSum =
        (from item in db.tbl_dppITHr
         where item.ProductionHour >= StartShift && item.ProductionHour <= EndDate
         select item).Sum(x => x.CastGood),

    CastScrap =
        (from item in db.tbl_dppITHr
         where item.ProductionHour >= StartShift && item.ProductionHour <= EndDate
         select item).Sum(x => x.Scrap),

    MachinedSum = 
    (
    from item in db.tbl_dppITHr
    where item.ProductionHour >= StartShift && item.ProductionHour <= EndDate
    select item).Sum(x => x.Machined),
};

        return View(GoodProduct);

The view i am using is strongly typed i with the following IEnmerable

@model IEnumerable<int?>

I have also tried

@model IEnumerable<MvcApplication1.Models.tbl_dppITHr>

This worked fine when i was passing a single value type but since i am doing a sum i get the following error.

The model item passed into the dictionary is of type '<>f__AnonymousType2`3[System.Nullable`1[System.Int32],System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[System.Nullable`1[System.Int32]]'.

Anyone know how to pass this var across?

Upvotes: 0

Views: 3029

Answers (1)

AdaTheDev
AdaTheDev

Reputation: 147224

As you have it now, you would need to use:

@model dynamic

as you are creating a dynamic object which you then pass to the view.

However, I prefer to create a strongly typed view model and pass that to the view. i.e.

public class GoodProductViewModel {
    public int CastGoodSum {get;set;}
    public int CastScrap {get;set;}
    public int MachinedSum {get;set;}
}

Then populate that in your controller...

var GoodProduct = new GoodProductViewModel
{
    CastGoodSum = ....,
    CastScrap = ...,
    MachinedSum = ...
};

return View(GoodProductViewModel);

And use @model GoodProductViewModel in your View

Upvotes: 3

Related Questions