我的数据库中有五个条目" Name"这一切都始于' pagetitle_dynamic _'并有不同的后缀。我必须写一些不正确的东西,因为只返回一个结果。有什么建议吗?
public ActionResult PageList()
{
var keys = db.Keys.ToList();
var prefix = "pagetitle_dynamic_";
var display = keys.Where(x => x.Name.StartsWith(prefix));
foreach (var item in display)
{
var viewModel = new PageListViewModel
{
PageTitle = item.Name
};
List<PageListViewModel> viewModelList = new List<PageListViewModel>();
viewModelList.Add(viewModel);
return View(viewModelList);
}
}
答案 0 :(得分:1)
您的代码格式不正确,如您所见。
foreach (var item in display)
{
var viewModel = new PageListViewModel
{
PageTitle = item.Name
};
List<PageListViewModel> viewModelList = new List<PageListViewModel>();
viewModelList.Add(viewModel);
return View(viewModelList);
}
您已将return View(viewModelList);
写入foreach循环,因为该方法仅在您将第一个列表成员添加到视图模型时结束。
一种可能的解决方案可能是:
public ActionResult PageList()
{
List<PageListViewModel> viewModelList = new List<PageListViewModel>();
var keys = db.Keys.ToList();
var prefix = "pagetitle_dynamic_";
var display = keys.Where(x => x.Name.StartsWith(prefix));
foreach (var item in display)
{
var viewModel = new PageListViewModel
{
PageTitle = item.Name
};
viewModelList.Add(viewModel);
}
return View(viewModelList);
}
答案 1 :(得分:0)
作为@blorgbeard mentioned,您需要在循环之外移动返回调用和列表构造。
public ActionResult PageList()
{
var keys = db.Keys.ToList();
var prefix = "pagetitle_dynamic_";
var display = keys.Where(x => x.Name.StartsWith(prefix));
var viewModelList = new List<PageListViewModel>();
foreach (var item in display)
{
var viewModel = new PageListViewModel
{
PageTitle = item.Name
};
viewModelList.Add(viewModel);
}
return View(viewModelList);
}
答案 2 :(得分:0)
你可以更轻松地做到:
public ActionResult PageList()
{
var keys = db.Keys.ToList();
var prefix = "pagetitle_dynamic_";
var display = keys.Where(x => x.Name.StartsWith(prefix));
var viewModelList = new List<PageListViewModel>();
return View(display.Select(item => new PageListViewModel
{
PageTitle = item.Name
}
).ToList());
}