这可能类似于 ASP.NET MVC - 填充常用下拉列表 。
我想填充 DropDownLists。其中一些是静态数据。其中一些来自数据库。有几次我发现自己忘记调用填充列表并相应设置 ViewBag 的代码。为此添加一个单元测试几乎是值得的。我认为这适合单元测试的唯一方法是将其放置在模型/服务中。对于这种事情有最佳实践吗?
This might be similar to ASP.NET MVC - Populate Commonly Used Dropdownlists.
I want to populate DropDownLists. Some of it is static data. Some of it comes from the Database. A couple of times I found myself forgetting to call the code that populates my lists and sets the ViewBag accordingly. It is almost worth adding a unit test for this. The only way I think that this suits a unit test is if you place it in model/service. Is there a best practice for this kind of thing?
发布评论
评论(3)
我建议数据包含在模型中,但可能由 html.helper 方法构建。这样,您就可以将管道标记保留在视图之外,并使控制器可以自由地调用必要的视图和模型。
当然,您也可以将其交给带有
>
模型的部分视图。猫和它们的皮肤:)
I'd suggest that the data is contained within the model but is perhaps constructed by a html.helper method. this way, you keep the plumbing markup out of the view and leave the controller free to invoke the neccesary view and model.
You could also of course hand it off to a partialview with an
<IList<SelectList>>
model.cats and their skin :)
如果您遵循该模式的精神,那么模型应该为视图提供呈现给用户所需的所有非静态内容。如果您有静态下拉列表,那么您可以说这些可以在标记内构建。如果您从操作中将
SelectList
传递给视图,那么我会将其粘贴在模型中以使事情变得更简单、更连贯。If you follow the spirit of the pattern then the Model should supply the View with everything it needs to present to the user that's not static. If you have static dropdown lists then you could say that these could be constructed within the mark-up. If you are passing a
SelectList
to the View from your Action then I'd stick it in the Model to make things simpler and more coherent.我的经验法则是,数据必须以某种方式位于模型中,要么作为准备使用的 SelectList,要么最坏的情况是在某个可以使用 LINQ 到对象调用轻松转换为 SelectList 的容器中。
最重要的是,视图永远不应该包含任何重要的代码。
编辑(回答您的评论):
我尽量不在模型中放入太多代码。模型更像是由控制器收集并由视图使用的一组简单数据。
对于简单和/或常见的事情(例如星期几),我相信 HTML 帮助器是最优雅的解决方案。请参阅 WayneC 在此问题中的回答。
My rule of thumb is that the data must somehow be in the model, either as a ready to use SelectList or at worst in some container that can easily be turned into a SelectList using a LINQ-to-object call.
The bottom line is that the view should never contain any non trivial code.
EDIT (answer to your comment):
I try not to put too much code in models. Models are more like a simple bunch of data gathered by the controller and used by the view.
Regarding simple and/or common things such as the days of week, I believe an HTML helper is the most elegant solution. See WayneC's answer in this question.