Giles
Giles

Reputation: 13

ASP.NET MVC - How to build custom viewmodels in C# to pass a data set to a strongly typed View?

I'm new to ASP.NET, C# and the MVC framework but have managed to build a site that works pretty well.

Now I am trying to create a reporting section for the site to display a table of information on all users and just can't get my head around creating custom model classes for the joined table data. I have seen lots of examples with one record but none with a full data set.

I am using the Entity framework and pulling my data out with:

var usersInfo = from c in _dataModel.UserProfile select new { c.Forname, c.Surname, c.aspnet_Users.UserName, c.Countries.CountryName, c.Specialities.SpecialityName};

The data returns fine, but it is of the type: 'System.Data.Objects.ObjectQuery1[<>f__AnonymousType65[System.String,System.String,System.String,System.String,System.String]]'

How would I get this into a type that I can pass back to a strongly typed View?

Thanks,

Giles

Upvotes: 1

Views: 413

Answers (1)

spender
spender

Reputation: 120450

Make a named class to hold the data that is currently encapsulated in the anonymous data you have selected:

public class MyClass
{
    public string Forename{get;set;}
    public string Surname{get;set;}
    //etc
}

var usersInfo = from c in _dataModel.UserProfile select new MyClass{ Forename=c.Forname, Surname=c.Surname, ...};

Now you've got a concrete type that you can throw around your app with ease. If you run into this a lot, refactoring tools such as Resharper can convert from anonymous to named types in a couple of clicks.

Upvotes: 3

Related Questions