Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should code to build view models go?

When building a view model in asp.net's MVC3, where should the code go to instantiate the objects of that view model? I am doing it mostly in the controller right now, aside from the code to query the database. Here is an example in code:

View Model:

public class WorkListVM
{
    //list for employees
    [Display(Name = "Select A Employee")]
    [Required]
    public int? EmployeeId { get; set; }
    public GenericSelectList EmployeeList { get; set; }
}

Controller Code:

        //build view model
        var vm = new WorkListVM();

        //build employee list
        vm.EmployeeList = new GenericSelectList(0,"-- Select Employee --");
        var employees = new List<Employee>();
        using (var gr = new GenericRepo<Employee>())
        {
            employees = gr.Get().ToList();
        }
        foreach(var employee in employees)
        {
            var gl = new GenericListItem();
            gl.Id = employee.EmployeeId;
            gl.DisplayFields = employee.FirstName + " " + employee.LastName;
            vm.EmployeeList.Values.Add(gl);
        }

Generic Select List is a simple class to hold the data that goes in the helper @html.dropdownfor's SelectList. I build these selectlist's, and also build similar data configurations for view models inside of the controller code. The controller hosting this code has a total of 109 lines of code, so it is not huge or out of control. However, I am always striving to reduce redundancy and sometimes the code in //build employee list ends up being copy pasted (ugh, i hate copy paste) into other controllers.

Is there a better place to have this code? Should I maybe be using the factory pattern to build the data for these selectlists / other view data objects?

EDIT

Thanks for all your help. Here is what I ended up doing. I ended up making a method inside the generic select list class very similar to the .ToSelectList(...) suggested by Richard and Jesse:

    public class GenericSelectList
{
    public List<GenericListItem> Values { get; set; }
    public int StartValue { get; set; }
    public string Message { get; set; }

    public GenericSelectList(int StartValue = 0, string Message = "select")
    {
        Values = new List<GenericListItem>();
        this.StartValue = StartValue;
        this.Message = Message;
    }

    public void BuildValues<T>(List<T> items, Func<T, int> value, Func<T, string> text) where T : class
    {
        this.Values = items.Select(f => new GenericListItem()
        {
            Id = value(f),
            DisplayFields = text(f)
        }).ToList();
    }
}
like image 998
Travis J Avatar asked Mar 16 '12 22:03

Travis J


1 Answers

If the business logic that goes into creating a view model is quite complex I generally extract it into a helper method that I can test independently of the controller.

However, that aside, your creation of the view model is perfectly fine within the controller as it is. As has already been noted, how your generating the select list could be made much simpler (not to mention reusable).

Here is a ToSelectList extension of IEnumerable along with an example of usage:

public static List<SelectListItem> ToSelectList<T>( this IEnumerable<T> enumerable, Func<T, string> value, Func<T, string> text, string defaultOption)
{
    var items = enumerable.Select(f => new SelectListItem()
                                          {
                                              Text = text(f) ,
                                              Value = value(f)
                                          }).ToList();

    if (!string.IsNullOrEmpty(defaultOption))
    {
                    items.Insert(0, new SelectListItem()
                        {
                            Text = defaultOption,
                            Value = string.Empty
                        });
    }

    return items;
}

Within your view model you could add a property like so:

IEnumerable<SelectListItem> Employees { get; set; }

Within your controller (i'm assuming that your repo is returning IEnumberable):

var employees = new IEnumerable<Employee>();
using (var gr = new GenericRepo<Employee>())
{
    employees = gr.Get();
}

vm.Employees = employees.ToSelectList(x=>x.FirstName + " " + x.LastName, x=>x.Id, "-- Select Employee --")

And then to setup your drop down list in the view it would look something like:

@Html.DropDownListFor(model => model.EmployeeId, Model.employees)
like image 124
Jesse Avatar answered Sep 21 '22 01:09

Jesse