5

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 hand, 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

4

5 回答 5

5

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.

于 2010-02-08T01:37:46.410 回答
2

这是一个特定于演示的方面,所以我更喜欢在视图中使用 Html 帮助器。所以我将一个集合传递给 View 并使用一个 html 辅助方法将项目映射到 SelectListItems。该方法可能看起来非常像这样:

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

问候。

于 2010-02-08T11:26:43.873 回答
1

我通常在操作或服务层中创建我的 SelectList,并通过 ViewData 将其传递给我的视图。我还让它成为视图模型和强类型视图的一部分。两种方式都在操作或服务层中创建它。

于 2010-02-08T04:37:50.843 回答
1

我将 SelectList 作为视图模型中的属性公开,并使用必要的存储库将其填充到操作中。我认为直接与存储库交互的代码应该也是负责填充的代码,无论是控制器操作还是服务层或其他任何东西。

我不认为直接从视图模型填充列表是一个好主意,因为它需要视图模型具有存储库依赖并进行数据库交互,而视图模型不应该负责这类事情。

如果您有多个 SelectList 字段并希望保持操作代码更清晰,您还可以创建一个单独的特殊对象,称为 Initializer 或类似的东西,它会执行所有填充和初始化。

于 2010-02-08T07:49:46.073 回答
0

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

于 2010-05-05T18:09:33.980 回答