Answer the question
In order to leave comments, you need to log in
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; }
Answer the question
In order to leave comments, you need to log in
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).
Можно и нужно, т.к. в противном случае получается несоблюдение принципа DRY, в больших проектах иметь тонну моделей и поддерживать все их в актуальном состоянии будет адом.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question