Return two lists to the view c# mvc
Solution 1
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
...
Solution 2
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.
Solution 3
Try using the dynamic type like ViewBag
You can access @viewbag in Razor View
Marc Howard
Analyst Programmer for Coutts & Co. B.Sc Computing (University of the West of England) 2012
Updated on June 04, 2022Comments
-
Marc Howard over 1 year
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()); }
-
Max about 10 yearsI wouldn't suggest ViewData, the first way, is the best way.
-
Tommy about 10 yearsAnd as an addendum, in order to access the list in the view, you would use syntax such as '@Model.Added' and '@Model.Removed'