用于选择列表的 ASP.NET MVC 模型与 ViewData
我有一个 ASP.NET MVC 应用程序,其中有很多下拉列表和多选列表。本质上,有很多选项列表。
我的问题是;将这些列表作为模型的一部分传递到视图还是作为 ViewData 更好?
我目前将它们作为 ViewData 传递,因为我在模型上并不真正需要它们,而且它们在模型上传递时似乎可能很庞大(我得到了选定的一个或多个项目,这确实是我所需要的)。缺点是,ViewData 需要在 View 上进行转换,这不如强类型模型那么好。
这里有最佳实践吗?即使对其中任何一个的利弊提出建议,我们也将不胜感激。
I have an ASP.NET MVC application with quite a few drop-down lists and multi-select lists. Essentially, a lot of lists of options.
My question is; is it better to pass these lists to the view as part of the Model, or as ViewData?
I am currently passing them as ViewData as I don't really need them on the model and they seem potentially bulky for passing around on the model (I get the selected item or items, which is really all I need). On the downside, ViewData needs casting on the View, which isn't as nice as the strongly typed model.
Is there a best practice here? Even suggestions of pros and cons for either of these would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议您使用 ViewModel 来传递该数据。将 ViewData 与“魔术字符串”一起使用很容易出错,我更喜欢使用智能感知而不是试图记住“魔术字符串”。并且您不需要在控制器中创建该 SelectList。只需使用一些 IEnumerable 并使用 ToSelectList 扩展方法视图中的 MvcContrib。
I recommend you to use ViewModels to pass that data. It's error prone to use ViewData with "magic strings" and I prefer to use intellisense instead of trying to remember that "magic strings". And you don't need to create that SelectLists in the controller. Just use some IEnumerable and use ToSelectList extension method from MvcContrib in the view.
如果我只有 1 个项目传递到视图,我倾向于使用 ViewData。因此,如果您要发送多个对象并且需要填充多个下拉列表,我将创建一个视图模型。我还将在 Web 应用程序项目中创建该视图模型,因此如果您的视图模型具有 SelectList 对象,则您不需要在域模型中引用 MVC dll。
I tend to use ViewData if I only have 1 item I'm passing to the view. So, if you're sending multiple objects and need to populate multiple dropdowns I would create a view model. I would also create that view model in the web app project so if your view model has SelectList objects you won't need a reference to the MVC dll in your domain model.