N
N
Nikolai Mokhov2015-05-08 11:59:26
ASP.NET
Nikolai Mokhov, 2015-05-08 11:59:26

Can a Model be used to interact with a View instead of a ViewModel?

Hello. In my ASP.NET MVC 5 projects, when creating a model, I immediately specify all the attributes I need, for example

[Required]
        [StringLength(maximumLength: 120, ErrorMessage = "Значение {0} должно содержать символов не менее {2}, и не более {1}.", MinimumLength = 10)]
        [Display(Name = "Название")]
        [DataType(DataType.Text)]
        public string Name { get; set; }

and use this model to generate the View.
But very often I see examples when Model and ViewModel are separated. So I wanted to ask what are the pros and cons of this approach, except for defining properties (fields) in the ViewModel that are not used in the Model (in the database)?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Stanislav Makarov, 2015-05-08
@Kolay_Net

The advantage is that in large projects you don’t want to make the structure and interface of the model dependent on the view to any extent. Look, for example, you have a Display or StringLength attribute - often such things are unnecessary in a business model. With this model, it is possible that code will work that has nothing to do with displaying data to the user, for example, some kind of background bot or statistics collector. Or, which is more common, a completely different representation will work with the same model - for example, you have one view "for everyone", i.e. for customers, for example, an online store, and the other for employees who serve orders. And they will display the same data about customers and orders in a completely different way.
Therefore, as a rule, it is more convenient to have an intermediate layer in the form of a ViewModel, which "closes" the data of the general model to a specific view. For example, I often do various calculated properties in the ViewModel that need to be displayed somewhere, even in a table. Those. in the business model, I have fuel consumption per kilometer, and the distance traveled, and in the ViewModel, in addition to this, I also have the total fuel consumption at the current time (which, of course, is calculated on the fly).

Артур Нуруллин, 2015-05-08
@Splo1ter

Можно и нужно, т.к. в противном случае получается несоблюдение принципа DRY, в больших проектах иметь тонну моделей и поддерживать все их в актуальном состоянии будет адом.

C
CrazyHorse, 2015-05-08
@CrazyHorse

А еще можно почитать на тему DDD

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question