如何使用View从多个表访问数据 [英] How to Access Data from Multiple Table using View
问题描述
Hello Everyone!
我试图使用ASP.NET MVC中的ViewModel从数据库中的多个表中获取数据。但是当我尝试检索数据时,我总是获得空值。数据库表有两个记录请参阅下面的代码并告诉我如何做到这一点,
我的ViewModel是
Hello Everyone!
I am trying to get Data from Multiple Tables in Database using ViewModel in ASP.NET MVC. But I always Get Null Value When I try to retrieve data Database table has Two Records Please see Below the Code and tell me how I can do it,
My ViewModel is
public class LMSViewModel
{
[Key]
public int LMSViewModelId { get; set; }
public List<Student> Students { get; set; }
public List<Department> Departments { get; set; }
public List<Teacher> Teahcers { get; set; }
public List<Course> Courses { get; set; }
}
MY Controller
MY Controller is
public ActionResult Index()
{
///LMSViewModel is my ViewModel Name
LMSViewModel Container = new LMSViewModel();
var DepteData = (from D in Db.Departments
select new
{
Name=D.DepartmentName,
Budget=D.DepartmentBudget,
Building=D.BuildingName
}).ToList();
//I also got error Here Error name is CS0029(Implicit Conversion)
//Container.Students =DepteData;
return View(DepteData);
}
请告诉我如何在View中显示多个。我在等您的回复感谢
Please tell me how to show multitable in View Using .I am waiting your Reply Thank
推荐答案
您需要选择特定对象 -
You need to select the particular object-
public ActionResult Index()
{
///LMSViewModel is my ViewModel Name
LMSViewModel Container = new LMSViewModel();
var DepteData = (from D in Db.Departments
select new Department
{
Name=D.DepartmentName,
Budget=D.DepartmentBudget,
Building=D.BuildingName
}).ToList();
Container.Departments = DepteData;
// same way query for the Students, Teachers, Courses and assign them to Container
return View(Container);
}
-KR
-KR
请参阅下面的实现如何传递多个结果集从控制器查看页面:
控制器
See below implementation how to pass multiple result set to View page from Controller:
Controller
public ActionResult Index()
{
///LMSViewModel is my ViewModel Name
LMSViewModel Container = new LMSViewModel();
var DepteData = (from D in Db.Departments
select new
{
Name=D.DepartmentName,
Budget=D.DepartmentBudget,
Building=D.BuildingName
}).ToList();
//I also got error Here Error name is CS0029(Implicit Conversion)
Container.Students =DepteData;
// Assign other property like teachers, departments, id and others to Container object.
return View(Container);
}
在Controller中我们只分配Students对象 - 你需要分配其他对象,如部门,教师。因此,您可以在视图页面中访问这些属性。
查看
In Controller we assign only Students object - you need to assign other objects like departments, teachers. So that you can access those property in view page.
View
@model MultipleModelDemo.ViewModel.LMSViewModel
@foreach (var item in Model.Students)
{
<div>@item.PropertyName</div>
}
@foreach (var item in Model.Departments)
{
<div>@item.PropertyName</div>
}
在视图页面中,您需要更改属性名称和ViewModel引用。你的需要。
此外请访问 ASP.NET视图中的多个模型MVC 4 / MVC 5 [ ^ ]
这篇关于如何使用View从多个表访问数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!