我如何生成数据库值选择列表? [英] How do I generate a select list from database values?

查看:124
本文介绍了我如何生成数据库值选择列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道什么是具有含有从数据库中值,而不会复制任何code窗体上的选择列表中的最佳方法。

I was wondering what is the best approach to having a select list on a form which contains values from a database without duplicating any code.

我可以用我的想法是有意义的是在控制器中加载这些数据,并把它传递给视图模型,让 SelectListFor<> 或任何在为了生成列表。然而,这意味着我必须复制所有的列表装载在GET和POST的两种方法。另一种方法我可以看到会通过数据库上下文到视图模型构造,并加载它的列表中,但是这则presents两个问题:

What I thought would make sense would be to load this data in the controller and pass it to a view model, so I can use SelectListFor<> or whatever in order to generate the list. However this means that I have to duplicate all the list loading in both the GET and the POST methods. The other way I can see would be to pass the database context into the view model constructor and have it load the list , but this then presents two more issues:

1)如果视图模型了解数据库上下文?

1) Should the view model know about the database context?

2)然后我不能用模型通过接受视图模型类型作为方法的参数绑定,因为它没有一个无参数的构造函数(如果我创建一个无参数的构造函数,那么它不会有名单,如果我要重新显示包含表单视图)。

2) I then cannot use model binding by accepting the view model type as a method argument because it does not have a no-argument constructor (if I create a no-argument constructor then it won't have the lists if I want to redisplay the view containing the form).

有没有更好的方法来做到这一点?这似乎是它必须是一个相当常见的场景和任何意见将AP preciated。

Is there a better way to do this? This seems like it must be a fairly common scenario and any advice would be appreciated.

推荐答案

我们通常通过被控制器中使用相同的方式为任何其他存储库交互ReferenceDataRepository实现我们的查找。该库通常使用(会话,AppFabric的等),你选择的缓存方案的抽象收到大量的predominantly静态只读数据呼叫,所以我们可以实现一个派生CachedReferenceDataRepository了这一点。

We typically implement our lookups through a ReferenceDataRepository that gets used within the controllers in the same way as any other repository interaction. This repository will usually recieve a high number of calls for predominantly static readonly data so we may implement a derived CachedReferenceDataRepository over this using an abstraction of your caching scheme of choice (Session, AppFabric etc).

这篇关于我如何生成数据库值选择列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆