ViewModels 是一种在 View 上表示数据的方式,您需要在其中显示来自 Models 的信息,请查看此问题以了解它们是什么:What is ViewModel in MVC?
在您的情况下,您可以创建一个简单的 ViewModel 来表示您需要在 Report_Main 上显示的数据,这可以通过以下方式轻松实现:
namespace MyProject
{
public class MyViewModel
{
public int ID { get; set; }
public System_Tracking Tracking { get; set; }
public Report_Login_Credentials Credentials { get; set; }
public Report_Type Type { get; set; }
public List<Report_Peramiter_Fields> Fields { get; set; }
public string Name { get; set; }
public string Location { get; set; }
}
}
它可能只是看起来像一个简单的模型,因为它只是一个视图使用,并且没有持久化。这就是模型和视图模型之间的区别。
从此您只需要一页,例如MyPage.cshtml,您可以在其中使用此模型,例如:
@model MyProject.MyViewModel
@{
ViewBag.Title = "MyPage";
}
@* your content here *@
@Model.ID <br>
@Model.Report_Type.Description
// Etc.
要传递此信息,您需要在控制器中进行,例如:
namespace MyProject
{
public class MyController : Controller
{
public ActionResult MyPage(int? Id)
{
var data = context.Report_Main.Find(Id); // Or whatever
var vm = new MyViewModel(){
Tracking = data.System_Tracking,
// ... populate the viewmodel here from the data received
};
return View(vm);
}
}
}
简而言之,ViewModels 允许您将所有数据绑定在一个模型中,并将其传递到可以静态表示它的视图上,当您不想直接表示或从用户那里获取数据时,您也可以使用它。访问模型。
编辑:您可以使用 C# 遍历 Razor 中的模型列表:
foreach(var item in Model.Fields)
{
<p>item.Peramiter</p>
}