# Is it “legit” to use a Linq query in a razor view?

I have a Linq query in my razor view like below. Its just getting contacts that belong in the group.

@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()))
{

///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?

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.

• The problem is that I do pass everything I need to the view. Everything in that model get used, but I just have to get it grouped based on that g.id. Would it be better to have a partial view with the group needed there? – smarble Oct 3 '14 at 21:14
• What if you were to group it before passing it to the view then give it to the view grouped, would that work? It's somewhat strange to have .Groups and then .Contacts that aren't grouped. Can you add some more of the code around this to the post? – Steve Michael Oct 3 '14 at 22:30

This is a relational way of thinking: you have several tables and they are connected using ids. But I think a better approach is object-oriented: you deal with objects that are connected using properties:

foreach (var contact in group.Contacts)
{
// Row output here
}


How exactly to implement that depends on how your model works, but if you're using some ORM, it can probably help you with this.