2

如果我的要求是从单独的 dll(DAL、域等)返回 webform、winform、wpf 表单等中的 DropDownlist 的数据。你会返回什么?

我可以使用:

SelectListItem[]

Ilist<SelectListItem>

IEnumerable<SelectListItem> 

和其他类似性质的,但我不喜欢“SelectListItem”与 System.Web.Mvc 命名空间相关联的方式。也许它只是我,但它似乎有点具体。我的网络表单可能甚至没有使用 MVC,尽管它仍然可以工作?

4

2 回答 2

0

我认为您已经回答了您自己的问题,因为从非 asp.net MVC 的应用程序可能使用的程序集中返回 SelectList 是不合适的。这甚至会导致 WPF 应用程序必须引用 System.Web.Mvc。

更合适的架构是返回某种类型的 IEnumerable,然后将其转换为当前应用程序类型的适当列表项类型。如果这对您更有帮助,这种转换可能发生在某种适配器层或通过扩展方法。

于 2011-03-26T19:55:49.723 回答
0

我遇到了同样的问题,我的解决方案是在服务层中创建一个小类并将数据映射到SelectListItem视图中的 s 。示例代码:

1)服务层中的代理类:

public class SelectListItemBase
{
    public String Value { get; set; }
    public String Text { get; set; }
}

2)视图模型:

public class FetchWordsIntegrationViewModel
{
    public IList<SelectListItemBase> WordTypes { get; private set; }

    public FetchWordsIntegrationViewModel()
    {
        WordTypes = new List<SelectListItemBase>();

        WordTypes.Add(new SelectListItemBase() { Value = "0", Text = Constants.Ids.SelectionListDefaultText });
        WordTypes.Add(new SelectListItemBase() { Value = ((int)FetchedWordType.ProperNoun).ToString(), Text = "Proper noun" });
        // other select list items here
    }
}

3) 动作中的代码

public ActionResult Index()
{
    var vm = theService.CreateViewModel();
    return View(vm);
}

4) 使用Automapper进行映射(这不是必需的,因为SelectListItem可以使用 LINQ 轻松生成 s)

Mapper.CreateMap<SelectListItemBase, SelectListItem>();

5)最后,来自视图的代码

@Html.DropDownListFor(m => m.WordTypes,
    (IEnumerable<SelectListItem>)Mapper.Map(
        Model.WordTypes, 
        typeof(IList<SelectListItemBase>), 
        typeof(IList<SelectListItem>))
)

这个简单的任务非常复杂,但允许所需的解耦,如果需要,还可以轻松映射其他属性。

于 2016-01-30T20:57:22.577 回答