I'm using a ViewModel to pass the data from two tables to the view. 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. Is it possible to use LINQ like where
or equal
to make this possible? 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:
@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. 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. 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. If done right, you should not need any linq queries in your Views.
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)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.