Wasser Trinker
Wasser Trinker

Reputation: 115

ASP.NET MVC 3 - Create a dynamic object only for return

I have a javascript application (ASP.net MVC 3 on the back end with SignalR) and i want to return only the fields that are needed (it must be dynamic).

I use the entity framework but i cant select only the specific columns because i need some fields for checking or something in the method that are no needed on the client side.

so, currently i make this:

    public void GetPerson(int personID)
    {
        // Some logic...

        // person is a entity from the entity framework (Person)
        dynamic p = new
        {
            ID = person.ID,
            FirstName = person.FirstName,
            LastName = person.LastName
        };

        Clients[Context.ConnectionId].loadPerson(p);
    }

But i'm not sure, if its a good practice (Performance etc.). Is there a better solution or can i still continue with the dynamic type?

Upvotes: 0

Views: 1446

Answers (3)

Nick Albrecht
Nick Albrecht

Reputation: 16938

The best practice with MVC, whether returning data to a view or to the client via JSON or even using SignalR, is to use a strongly typed object. Just create a ViewModel specifically for the data you want to return and use that. I usually name these classes using a convention of [Controller][Action]ViewModel. So one might be MemberDetailsViewModel.

The benefits include the compile time checking, easier serialization and, less problems when it comes to modifications later.

I tried exactly what your doing when I first started playing around with MVC. trust me, it's not worth the convenience you perceive to be getting now.

If your data being returned MUST be dynamic, you may want to try returning a collection of key value pairs.

Upvotes: 0

Davin Tryon
Davin Tryon

Reputation: 67316

Are you using the ExpandoObject?

Going by your example, maybe use just an anonymous type instead of a dynamic type.

 var p = new
        {
            ID = person.ID,
            FirstName = person.FirstName,
            LastName = person.LastName
        };

This will make sure that you still get compile-time checking. However, either should work. See this for more detail on anonymous vs dynamic.

Upvotes: 2

Jon
Jon

Reputation: 40062

Looks fine to me. If you need the other columns then return them and do what you need to do with them and then as you are doing create a anonymous person and pass it in.

Upvotes: 0

Related Questions