从DAL或Domain返回SelectListItem或等效

时间:2011-03-26 19:47:07

标签: c# model-view-controller data-access-layer listitem

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

我可以使用:

SelectListItem[]

Ilist<SelectListItem>

IEnumerable<SelectListItem> 

和其他类似性质但我不喜欢'SelectListItem'与System.Web.Mvc命名空间绑定的方式。也许它只是我,但它似乎有点具体。我的webform甚至可能没有使用MVC,虽然它仍然有用吗?

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

我遇到了同样的问题,我的解决方案是在服务层创建一个小类,并将数据映射到视图中的<body ng-controller="MainCtrl"> <input type=number ng-model="someValue" /> <button ng-click="addPlant()">CLICK ME</button> <div>{{result}}</div> </body> 。示例代码:

1)服务层中的代理类:

SelectListItem

2)视图模型:

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

3)行动中的代码

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

4)使用Automapper进行映射(这不是必需的,因为public ActionResult Index() { var vm = theService.CreateViewModel(); return View(vm); } 可以使用LINQ轻松生成)

SelectListItem

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

Mapper.CreateMap<SelectListItemBase, SelectListItem>();

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

相关问题