Where should the code work to create view models?

When building a view model in asp.net MVC3, where should the code go to instantiate the objects of this view model? I am doing this mainly in the controller right now, except for the code to query the database. Here is a sample 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);
        }

- , @html.dropdownfor SelectList. , . , , 109 , . , , //build employee list , (ugh, hate copy paste) .

? factory selectlists/ ?

. . , , .ToSelectList(...), :

    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();
    }
}
+5
4

-, , , , .

, , , . , ( ).

ToSelectList IEnumerable :

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;
}

:

IEnumerable<SelectListItem> Employees { get; set; }

( , 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 --")

, , :

@Html.DropDownListFor(model => model.EmployeeId, Model.employees)
+2

- , . .

, , , , .

, . , , , () . , .

+2

1 - IEnumerable<Employee> IQueryable<Employee>, GenericSelectList. - , .. ; . - .

2 - , IEnumerable<T> GenericSetList Expression. . , .. . , 1, 1 . - ..

3 - factory, ViewModels.

, / .

- , . 2 ( VB, # ). .

Imports System.Runtime.CompilerServices
Imports System.Linq.Expressions

Module IQueryableExtensions

    <Extension()>
    Public Function ToSelectList(Of T)(source As IEnumerable(Of T), nameExpression As Expression(Of Func(Of T, String)), valueExpression As Expression(Of Func(Of T, String)), selectedExpression As Expression(Of Func(Of T, Boolean)), additionalItems As IEnumerable(Of SelectListItem)) As IEnumerable(Of SelectListItem)
        Return additionalItems.Union(
            source.Select(Function(x) New SelectListItem With {
                              .Text = nameExpression.Compile.Invoke(x),
                              .Value = valueExpression.Compile.Invoke(x),
                              .Selected = selectedExpression.Compile.Invoke(x)
                          }
                      )
                  )
    End Function

End Module

:

    Dim People As New List(Of Person) From {New Person With {.Name = "Richard", .ID = 1}}

    Dim sl = People.ToSelectList(Function(p) p.Name,
                                 Function(p) p.ID,
                                 Function(p) p.ID = 1,
                                 {New SelectListItem With {.Value = 0,
                                                           .Text = "Please Select A Person"}})
+2

, , , .

, , cookie . .

( , : p)

, -. , , , .

plus, you get a good sense of well-being, when after 3 days you need to use the method and everyone is waiting for it there.

Martyn

+1
source

All Articles