August 14, 2009

Protecting your MVC Model with anonymous types

Filed under: C# — Tags: , , — rqmedes @ 12:01 pm

Anonymous classes can be a great way to protect your models from being polluted by any view specific requirements.
Lets say you have a Product model that you want to present as a list in a table.


You now want to add some extra information to present any pre selected items.
By creating an anonymous type you can easily extend your product to add the additional information, Selected.

var test = new { Product = product, Selected = true};

Combining this with Linq makes it easy to return a list that contains the products and any other information required by the view engine

var selectedId = 3;
var products = (from p in _productRepository.GetAll()
select new { Product = p, Selected = p.Id == selectedId });

This will set selected as true for the product with the Id of 3.



Create a free website or blog at WordPress.com.