简体   繁体   English

在View中处理ViewModel中的数据

[英]Handle data from ViewModel in View

I'm using a ViewModel to pass the data from two tables to the view. 我正在使用ViewModel将数据从两个表传递到视图。 One table contains name of the staff and the second table contains data like number of hours they work per week. 一个表包含职员的姓名,第二个表包含诸如每周工作时间之类的数据。 When I list the names from one table I also want to show the working hours that match that persons ID. 当我从一张表中列出姓名时,我还想显示与该人员ID匹配的工作时间。 Is it possible to use LINQ like where or equal to make this possible? 是否有可能使用LINQ像whereequal使这个可能吗? Could someone show me a simple sample? 有人可以给我看一个简单的样本吗?

EDIT: Are there better ways to do this? 编辑:有更好的方法做到这一点吗? Should I handle this in the Controller instead? 我应该在控制器中处理吗?

This is the code I'm using so far in the View: 这是我到目前为止在View中使用的代码:

@foreach (var item in Model.resourceList)
{
<p>@item.FirstName</p>
}

@foreach (var item in Model.activityList)
{
<p>@item.NumberOfHoursPerWeek</p>
}

If you're looping through this: 如果您正在遍历此:

@foreach (var item in Model.resourceList)
{
    ...
}

Then within that loop you can match any element in Model.activityList just like any other LINQ query. 然后,在该循环中,您可以像其他任何LINQ查询一样匹配Model.activityList中的任何元素。 Perhaps something like this?: 也许是这样的:

@Model.activityList.Single(a => a.SomeID == item.SomeID).NumberOfHoursPerWeek

The actual comparison (in this example, a.SomeID == item.SomeID ) is up to you, as is the logic for the records you want to find ( .Where() , .Single() , .First() , etc. depending on the behavior you expect) is up to you. 实际的对比(在这个例子中, a.SomeID == item.SomeID )是你,因为是你要找到(记录的逻辑.Where() .Single() .First()等取决于您的预期行为)。 But finding an element in a collection is the same in this view code as it would be in any server-side code. 但是,在此视图代码中与在任何服务器端代码中一样,在集合中查找元素是相同的。

Ignoring all design issues, here is a solution: 忽略所有设计问题,这是一个解决方案:

@foreach (var item in Model.resourceList)
{
    @{
        var numberOfHours = Model.activityList.First(_ => _.UserID == item.ID).NumberOfHoursPerWeek;
    }
    <p>@item.FirstName</p>
    <p>@numberOfHours</p>
}

However, the View should usually be kept as simple as possible. 但是,视图通常应保持尽可能简单。 The ViewModel is responsible for preparing the data for the View in an easily consumable form. ViewModel负责以易于使用的形式为View准备数据。 If done right, you should not need any linq queries in your Views. 如果操作正确,则您的视图中不需要任何linq查询。

you can use it like this 你可以这样使用

with if 与如果

//just an example to make condition true not displaying the exact Property or condition
@if (true)
{
    Model.Where(model=>model.UserID==User.UserID)
}

or with loop 或循环

 @foreach (var item in Model.resourceList)
 {
     //just an example not displaying the exact Property
     Model.Where(model=>model.UserID==User.UserID)
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM