开发者

ASP.net MVC: Creating SelectList in the view or action?

I'm just wondering where people are creating their SelectList - in the action or the view.

I have seen examples of both and the one that makes the most sense to me is doing it in the action and have the view model have a property of type SelectList.

On the other ha开发者_C百科nd, I have seen examples where people have the view model have a property of SelectList and the SelectList is populated within the view model (either in the constructor or via lazy loading). I like this idea as it means there is less code in my actions...

In short I was just wondering what people are doing atm.

Cheers Anthony


Create your SelectList in the controller (by looking up your list of items from your model repository), and pass it to the view as either a ViewData object, or as part of your strongly-typed ViewModel.


It´s a presentation-specific aspect, so I prefer to do it in the View, using an Html helper. So I pass a collection to the View and use a html helper method to map the items to SelectListItems. The method could look very much like this:

public static IList<SelectListItem> MapToSelectItems<T>(this IEnumerable<T> itemsToMap, Func<T, string> textProperty, Func<T, string> valueProperty, Predicate<T> isSelected)
{
    var result = new List<SelectListItem>();

    foreach (var item in itemsToMap)
    {
        result.Add(new SelectListItem
        {
            Value = valueProperty(item),
            Text = textProperty(item),
            Selected = isSelected(item)
        });
    }
    return result;
}

Regards.


I typically create my SelectList in the action or service layer and pass it to my view via ViewData. I've also made it a part of a view model and a strongly typed view. Both ways create it in the action or service layer though.


I have the SelectList exposed as a property in the view model and populate it in the action using the necessary repository. I think that the code that interacts directly with the repositories should be the one that is also responsible with populating, be it the controller actions or service layer or whatever else.

I don't think that populating the list directly from the view model is a good idea, because it would require the view model to have a repository dependency and do database interactions and the view model should not be responsible for this kind of things.

You could also create a separate special object, called Initializer or something like that, that does all the populating and initializations, if you have multiple SelectList fields and want to keep your actions code cleaner.


Neither, create it in a separate class, look here How to map View Model back to Domain Model in a POST action?

I use an IBuilder interface in the controller and do all the building of entities/viewmodels in the implementation of this Builder

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜