ASP.NET MVC ViewData 和视图模型最佳实践
最初的情况是我将领域模型映射到表示模型。
我必须显示带有文本框和下拉列表的更新/创建公式。
视图模型应该包含下拉列表的列表还是应该使用 ViewData 传递下拉列表的数据?
什么时候应该使用 ViewData,什么时候不应该使用它?
像下拉列表这样的输入字段应该有单独的视图模型吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我倾向于尝试尽可能少地使用 ViewData,因为您总是需要转换值,您需要对空值或不存在的键进行错误检查,并且在我看来它会使视图变得混乱。
我倾向于尽可能尝试使用视图模型,因为我发现将视图强烈键入模型是一种更简洁的方法。
我会将尽可能多的数据放入视图模型中,但仅限于有意义的数据。对于不应该属于视图模型的数据,我将作为 ViewData 传入,但会尝试将数量保持在最低限度。
至于您对输入字段的问题,如果它们都是相关的,我会为此创建一个 ViewModel,而不是在 ViewData 中传递 5 或 10 条数据,因为从逻辑上将它们分组在一个地方是有意义的。这确实是一个偏好问题,但我发现这种方法最适合我。
I tend to try and use ViewData as little as possible since you always need to cast values, you need to do error checking for nulls or for keys that don't exist and it clutters the views in my opinion.
I tend to try and use viewmodels whenever possible since I find strongly typing the view to the model as a cleaner approach.
I would put as much of the data into the viewmodel as possible, but only what makes sense. For data that shouldn't belong in the viewmodel I would pass in as ViewData, but would try to keep the amount to a minimum.
As far as you question goes for input fields, if they are all related I would make a ViewModel for that instead of passing in 5 or 10 pieces of data in the ViewData since logically grouping them in one place would make sense. It really is a matter of preference, but I found this approach to be the best for me.
这确实是个人选择。 ViewData 的缺点是它是弱类型的并且需要强制转换。
It's personal choice really. The disadvantage of ViewData is that it's weakly typed and requires casting.
您可能想看看 NerdDinner,特别是 DiningFormViewModel 和列表可供选择的国家。基本上,他们有一个 Dining 模型(用于索引视图,需要一个集合)以及一个 DiningFormViewModel,其中包含一个 Dining 实例和一个国家/地区的 SelectList。当然,创建视图(恰当地命名为dinnerform)是强类型的,并且采用dinnerFormViewModel。
You might want to take a look at NerdDinner, in particular the DinnerFormViewModel and the list of countries to choose from. Basically, they have a Dinner model (used for the index view, where they need a collection) plus a DinnerFormViewModel which contains a single Dinner instance and a SelectList for the countries. The create view (aptly named DinnerForm) is, of course, strongly typed and takes a DinnerFormViewModel.
我在这里发现了一些非常有趣的东西... http://weblogs.asp.net/rashid/archive/2009/11/27/extending-asp-net-mvc-2-templates.aspx
正是我所需要的。
I found something very interesting here ... http://weblogs.asp.net/rashid/archive/2009/11/27/extending-asp-net-mvc-2-templates.aspx
Exactly what I need.
您应该将该列表作为模型的一部分传递。或者,如果列表非常普遍(例如,状态列表或是/否列表),您可以在静态类中创建一个静态列表,该静态列表可以在 ViewPage 中直接引用。我不明白为什么你想通过 ViewData 传递它,因为你必须在 ViewPage 中投射你的列表。
You should pass the list as part of your Model. Or, if the list is pretty pervasive (like, say, a list of States or a Yes/No list), you can create a static list in a static class that can be referenced directly in your ViewPage. I don't see why you'd want to pass it via ViewData, as you'd have to cast your list in your ViewPage.