ASP.NET MVC ViewData and Best Model Viewing Methods

The initial situation is that I am matching my domain model with the presentation model.

I need to display an update / create a form with text fields and a drop-down list.

If the viewmodel contains a list for a drop-down list, or should I pass data for a drop-down list using ViewData?

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

Should input fields like dropdownlists have a separate view model?

+4
source share
5 answers

I try to use ViewData as little as possible, since you always need to set values, you need to perform error checking for zeros or for keys that do not exist, and in my opinion, they are cluttering the eyes.

I try to use viewmodels as often as possible, since I find strongly typing the model view as a cleaner approach.

I would put as much data as possible in the viewmodel, but only what makes sense. For data that should not be related to the viewmodel, I would go as ViewData, but try to minimize it.

As far as you doubt the input fields, if they are all connected to each other, I would do a ViewModel for this instead of transferring 5 or 10 pieces of data to ViewData, since logical grouping them in one place would make sense. It really is a matter of preference, but I found this approach the best for me.

+4
source

This is a personal choice. The disadvantage of ViewData is that it is weakly typed and requires casting.

+2
source

Perhaps you should take a look at NerdDinner , specifically the DinnerFormViewModel and a list of countries to choose from. Basically, they have the Dinner model (used for the index view where they need the collection) plus the DinnerFormViewModel, which contains one instance of Dinner and SelectList for countries. The create view (aptly named DinnerForm) is, of course, strongly typed and accepts the DinnerFormViewModel.

+2
source

I found something very interesting here ... http://weblogs.asp.net/rashid/archive/2009/11/27/extending-asp-net-mvc-2-templates.aspx

That's what I need.

+2
source

You must pass the list as part of your model. Or, if the list is fairly common (for example, 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 understand why you want to pass it through ViewData, since you will need to display the list in your ViewPage.

+1
source

Source: https://habr.com/ru/post/1313252/


All Articles