Where should selectlist logic sit in ASP.NET MVC, view, model or controller?
Asked Answered
F

2

4

I feel my question is close to this one, but I want a more general discussion on where code like this should sit. Asp.Net MVC SelectList Refactoring Question?

I currently create my selectlists directly on my entity model, like so.

public SelectList taskDeadlineTime
    {
        get { return new SelectList(TimeDictionary, "Value", "Key", this.getDeadlineTime()); }
    }

This feels a bit wrong, as if I am performing view work, inside my model.

However it does mean that I can just get the property, and my selectlist is there.

Now, should I put this logic in my controller (more code to write) or view (feels wrong, and messy) or just be doing it in a different way.

The reason I am looking this now, is because I am working with comparing two copies of the same object entity, and having select lists as part of the getter directly means it doesn't work. I know I could modify this comparison to handle this, but it just feels wrong to do something visual in the model (unless the preparation of the select list is the correct thing to have in the model)

Fieldfare answered 19/9, 2010 at 17:47 Comment(0)
P
7

I usually put this into the view.

ViewModel:

public IEnumerable<Foo> TaskDeadlineTimes { get; set; }

View:

<%= Html.DropDownListFor(
    x => x.SelectedValue, 
    new SelectList(Model.TaskDeadlineTimes, "Value", "Key")
) %>

And the controller takes care of setting this property value using a repository.

Pharyngo answered 19/9, 2010 at 17:51 Comment(1)
This makes sense in a lot of ways, since you can also set selected values as the 4th parameter in the view. But wouldn't it be faster if you just provide the selectlist to the view, to get rid of the unused properties overhead?Husky
C
0

We have additiona layer which we call Builders.

Controller create builder and pass necessary information to it.

Builder interacts with context (current user, his role, etc) + data layer and generate Model with all valid data.

Than controller pass this model to View.

Carnap answered 19/9, 2010 at 18:3 Comment(1)
I do something similar except I've got builders at the action filter level instead of service/controller level. The controller can return a view model with attributes and null values and the proper builders get activated to fill in the missing data.Cleodell

© 2022 - 2024 — McMap. All rights reserved.