Search code examples
c#model-view-controllercontrollerout

Proper way of getting lots of data from a method


In an MVC project, in my controller, I would like to get data to use in the view. Lets say I want to retrieve a List<string> and an int.

My controller's method declaration is similar to this.

void GetFooData(int id, out List<string> listData, out int aValue);

In the view I am using as so:

List<string> data;
int value;
controller.GetFooData(myId, data, value);

I do not like this approach. How can I retrieve data in a prettier way without using a data wrapper class?


Solution

  • Despite you not using the MVC pattern correctly, in general, there are a lot of ways to return multiple things from a method. Typically one of:

    • Use out parameters (as you did above)
    • Return a Tuple to hold multiple items
    • Define and return a wrapper class to hold multiple items in its properties (this is classically the 'best practice')
    • Return a dynamic and/or ExpandoObject

    There are probably more that I can't think of right now...