ASP.NET MVC ViewData and view model best practices

2019-05-08 06:15发布

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

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

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

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

Shall input fields like dropdownlists have a seperate view model?

5条回答
Melony?
2楼-- · 2019-05-08 07:03

It's personal choice really. The disadvantage of ViewData is that it's weakly typed and requires casting.

查看更多
Melony?
3楼-- · 2019-05-08 07:05

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.

查看更多
再贱就再见
4楼-- · 2019-05-08 07:09

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.

查看更多
淡お忘
5楼-- · 2019-05-08 07:18

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.

查看更多
我欲成王,谁敢阻挡
6楼-- · 2019-05-08 07:19

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.

查看更多
登录 后发表回答