我有两个列表,我想要返回到视图,'添加'和'删除'。但是目前我只能返回“添加”#39;或者'删除'。我怎样才能在一个对象中返回?我对MVC很新,所以如果这段代码很乱,请道歉!
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());
}
答案 0 :(得分:12)
强烈键入您的视图,使其成为关联模型,该模型是包含两个列表的自定义对象。注意,这样的对象通常被称为“viewModel”。
示例:
您的viewModel:
public class MyViewModel
{
public List<X> Added { get; set; }
public List<X> Removed { get; set; }
}
你的控制器:
public ActionResult Index()
{
var viewModel = new MyViewModel
{
Added = ...,
Removed = ...
};
return View(viewModel);
}
您的观点:
@model XXXXX.MyViewModel
...
答案 1 :(得分:6)
为什么不让ViewModel包含这两个列表
return View(new MyModel{List1 = list1,List2 = list2});
或
ViewData["List1"] = list1;
ViewData["List2"] = list2;
return View();
看看这里:http://www.howmvcworks.net/OnViews/BuildingAStronglyTypedView
我想你想要第一个。
答案 2 :(得分:1)
尝试使用ViewBag等动态类型
您可以在Razor View中访问@viewbag