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

喜夏-厌秋 提交于 2019-12-22 08:22:31

问题


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)


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/3746777/where-should-selectlist-logic-sit-in-asp-net-mvc-view-model-or-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!