patterncsharpMinor
Is it "legit" to use a Linq query in a razor view?
Viewed 0 times
linqquerylegitviewuserazor
Problem
I have a Linq query in my razor view like below. Its just getting contacts that belong in the group.
The code I have works just fine, but the question is: Is it good practice to be using Linq in a view like that? If not, how would that be handled in the model and/or controller?
@using (var tabs = Html.Bootstrap().Begin(new Tabs("TabStripId")))
{
foreach (var g in Model.Groups)
{
@tabs.Tab(g.GroupName)
}
foreach (var g in Model.Groups)
{
using (tabs.BeginPanel())
{
using (Html.Bootstrap().Begin(new Table().Striped()))
{
///Table header here
///The line in question
var m = Model.Contacts.Where(x => x.GroupId == g.Id);
foreach (var item in m)
{
/// Row output here
}
}
}
}
}The code I have works just fine, but the question is: Is it good practice to be using Linq in a view like that? If not, how would that be handled in the model and/or controller?
Solution
This is not an ideal way to do things. The model passed to your view should only have what you need for the view.
There are a few different things going on here. One is searching for the information and two is displaying it in your view. The solution will depend on the context in which it is happening.
One option is that you can change your service to be searchable on GroupId. This way only the information you need is passed back.
If you get an entire object back from your service and just want to filter the contacts on that more complex model, you could create a repository that does that filtering or use a ViewModel.
The main thing here is that you never want to do this type of filtering in your view. Only send your view the data that it needs.
There are a few different things going on here. One is searching for the information and two is displaying it in your view. The solution will depend on the context in which it is happening.
One option is that you can change your service to be searchable on GroupId. This way only the information you need is passed back.
If you get an entire object back from your service and just want to filter the contacts on that more complex model, you could create a repository that does that filtering or use a ViewModel.
The main thing here is that you never want to do this type of filtering in your view. Only send your view the data that it needs.
Context
StackExchange Code Review Q#64656, answer score: 5
Revisions (0)
No revisions yet.