Start with refactoring and put the right logic in the right place. This LINQ query has nothing to do with the view. The view should not make any LINQ queries or anything else to retrieve data. It is assumed that the view must work with the data that it passes to it from the controller action in the form of a view model. The controller action builds and passes an adapted view model that you define for the view.
So, as always, you start by defining a presentation model that will be adapted to the requirements of your presentation:
public class MyViewModel { public IEnumerable<Brand> Brands { get; set; } }
then you write a controller action that populates this view model and passes it to the view:
public ActionResult Foo() { IEnumerable<products_comparison.Models.Product> products = ... var model = new MyViewModel { Brands = (from r in Model select r.Brand).Distinct() }; return View(model); }
that view:
@model MyViewModel <table> <tr> <th> Brand </th> </tr> @Html.DisplayFor(x => x.Brands) </table>
and finally, you can define an appropriate display template that will be automatically displayed for each element of the Brands collection of your view model ( ~/Views/Shared/DisplayTemplates/Brand.cshtml ):
@model Brand <tr> <td> @Html.DisplayForModel() </td> </tr>
Darin Dimitrov
source share