ASP.NET MVC的ViewData和视图模型的最佳实践 [英] ASP.NET MVC ViewData and view model best practices

查看:90
本文介绍了ASP.NET MVC的ViewData和视图模型的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最初的情况是,我在我的域模型映射到presentation模式。

The initial situation is that I map my domain model into a presentation model.

我要显示一个更新/创建文本框和一个DropDownList公式推。

I have to display an update/create formular with textboxes and a dropdownlist.

如果视图模型包含一个列表DropDownList的,或者我应该使用的ViewData传递数据的DropDownList的?

Should the viewmodel contain a list for the dropdownlist or should I pass the data for the dropdownlist by using ViewData?

我什么时候应该使用的ViewData我时,不应使用它呢?

When should I use ViewData and when should I not use it?

必如dropdownlists输入字段有一个单独的视图模型?

Shall input fields like dropdownlists have a seperate view model?

推荐答案

我倾向于尝试使用的ViewData,尽量少,因为你总是需要转换值,你需要做的错误检查空或键说唐 ŧ存在,它杂波在我看来看法。

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.

我倾向于尝试使用的ViewModels只要有可能,因为我觉得强烈键入视图模型作为清洁剂的做法。

I tend to try and use viewmodels whenever possible since I find strongly typing the view to the model as a cleaner approach.

我把尽可能多的数据到视图模型成为可能,但只有情理之中的事情。对于不应在视图模型属于数据我将通过在作为ViewData的,但会尝试量保持在最低限度。

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.

至于你的问题也适用于输入字段,如果他们都与我会做一个视图模型为,而不是5或10个在ViewData的数据传递,因为逻辑分组他们在一个地方才有意义。这真的是preference的事,但我发现这种方法是最适合我的。

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.

这篇关于ASP.NET MVC的ViewData和视图模型的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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