I want to create a view using razor template, but I do not want to write a class for model, because in many views i will have many queries which will be returning diferent models.
For example I have a linq query:
from p in db.Articles.Where(p => p.user_id == 2)
select new
{
p.article_id,
p.title,
p.date,
p.category,
/* Additional parameters which arent in Article model */
};
I need to write a View for this query. This query returns a Articles.
Now I dont know how should looks like a model definition.
I tried to use this deffinition:
@model System.Collections.IEnumerable
But then I had an erros than fileds doesnt exists in object type:
*CS1061: 'object' does not contain a definition for 'addition_field' and no extension method 'addition_field' accepting a first argument of type 'object' could be found*
This is my model for which I do not want to write a next model. Of course
It seems you can't pass anonymous types but if you just want the values of the type you might pass an enumerable of an object array to view.
View:
Controller:
I think this is an even better solution:
http://buildstarted.com/2010/11/09/razor-without-mvc-part-iii-support-for-nested-anonymous-types/
This allows for nested anonymous types, which the aforementioned expando-object solution won't handle.
The short answer is that using anonymous types is not supported, however, there is a workaround, you can use an
ExpandoObject
Set your model to
@model IEnumerable<dynamic>
Then in the controller