Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return two lists to the view c# mvc

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());

    }
like image 973
Marc Howard Avatar asked Nov 07 '13 15:11

Marc Howard


2 Answers

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
...
like image 82
ken2k Avatar answered Sep 20 '22 20:09

ken2k


Why not having a ViewModel containing these 2 lists

return View(new MyModel{List1 = list1,List2 = list2});

or

ViewData["List1"] = list1;
ViewData["List2"] = list2;
return View();

have a look here: http://www.howmvcworks.net/OnViews/BuildingAStronglyTypedView

I think you want the first one.

like image 41
Avi Fatal Avatar answered Sep 20 '22 20:09

Avi Fatal