Return two lists to the view c# mvc

Marc Howard picture Marc Howard · Nov 7, 2013 · Viewed 13.5k times · Source

I have two lists that i want to return to the view, 'added' and 'removed'. However currently i can only return either the 'added' or 'removed'. How can i return both in one object? I am very new to MVC so apologies if this code is messy!

public ActionResult Index()
    {
        // Excel upload history

        var fptexcel = db.FPTStaticDataRatedFinancialAssetBase
                       .OrderBy(e => e.FORATExcelId)
                       .Select(e => e.FORATExcelId).Max();

        var fptexcelprevious = fptexcel - 1;

        var newassets = db.FPTStaticDataRatedFinancialAssetBase.OfType<FPTStaticDataRatedFinancialAssetBase>()
                        .Where(c => c.FORATExcelId == fptexcel || c.FORATExcelId == fptexcelprevious)
                        .GroupBy(x => x.Name)
                        .Where(c => c.Count() == 1)
                        .Select(y => y.FirstOrDefault()).ToList();

        var added = db.FPTStaticDataRatedFinancialAssetBase.OfType<FPTStaticDataRatedFinancialAssetBase>()
                         .Where(x => x.FORATExcelId == fptexcelprevious)
                         .Select(x => x).ToList();

        var removed = db.FPTStaticDataRatedFinancialAssetBase.OfType<FPTStaticDataRatedFinancialAssetBase>()
                         .Where(x => x.FORATExcelId == fptexcel)
                         .Select(x => x).ToList();

        return View(newassets.Except(added).ToList());

    }

Answer

ken2k picture ken2k · Nov 7, 2013

Strongly type your view so it as an associated model that is a custom object that contains both lists. Note such an object is often referred as a "viewModel".

Example:

Your viewModel:

public class MyViewModel
{
    public List<X> Added { get; set; }
    public List<X> Removed { get; set; }
}

Your controller:

public ActionResult Index()
{
    var viewModel = new MyViewModel
    {
        Added = ...,
        Removed = ...
    };
    return View(viewModel);
}

Your view:

@model XXXXX.MyViewModel
...