我正在尝试将至少两个表的内容添加到 VS2022 中的 C# 和 ASP.NET MVC 应用程序的视图中。我创建了模型登录和类别,然后添加了一个名为
BothModels
的新模型,如下所示:
public class BothModels
{
List<LoginModel>? LoginList { get; set; }
List<CategoriesModel>? CategoriesList { get; set; }
}
然后在我的控制器中,我尝试将两个集合添加到
BothModels
以传递到我的视图。这是我到目前为止得到的代码:
List<LoginModel> loginDtl = getLogin();
List<CategoriesModel> ctgDtl = geCategory();
BothModels bothModels = new BothModels();
.
// How to add both lists to bothModels here?
.
return bothModels;
我需要找到一种方法将两个列表添加到
bothModels
,然后在传递到视图后如何显示这两个列表。
视图看起来像这样:
@Model BothModels
@foreach (var line in @Model)
{
line.loginModel.User
//...
}
有人可以帮我完成代码吗,因为我尝试了多种不同的方法但没有成功
您需要将
ViewModel
中的两个列表指向检索到的列表,如下所示:
List<LoginModel> loginDtl = getLogin();
List<CategoriesModel> ctgDtl = geCategory();
BothModels bothModels = new BothModels();
// This is how you can add both the list in your viewmodel
bothModels.LoginList=loginDtl;
bothModels.CategoriesList=ctgDtl;
return bothModels;
视图将如下所示:
@Model BothModels
@foreach (var line in @Model.LoginList)
{
line.loginModel.User
//...
}
@foreach (var line in @Model.CategoriesList)
{
line.CategoriesModel
//...
}