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.



Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: