How do you name your ViewModel classes?

2019-02-21 13:08发布

问题:

What kind of naming convention is appropriate for ViewModel classes?

Example: for HomeController, Index view? HomeIndexViewModel doesn't seem right.

回答1:

EmployeesViewData.

That's what I use and what I've seen in sample applications as well.

About your added example: Imho the name of the class should specify what kind of data it contains. "....IndexViewData" is rather meaningless. What exactly is displayed on that page? Try to summarize it in 1 or 2 word(s) and add 'ViewData' behind it.

Or else just take the name of the controller and drop the "index". HomeViewData sounds fine to me.



回答2:

I use the following pattern because it's clear and unambiguous :

  • Model : Foo
  • View : FooView
  • ViewModel : FooViewModel


回答3:

I try to keep my presentation model names agnostic of the kind of presentation they will be presented with. I may use my model object for an ASP.NET view initially, but later on I may also use it in a WCF or WinForms app. I try to name my models such that they logically describe what they contain, without muddying them up with "ViewData", "ViewModel", "Model", etc.

Examples:

ProductsWithPageInfo
ProductWithAttributesAndTags
ClientAndBillingDetail
UserAccountWithAssociatedGroups

Etc.



回答4:

I prefer HomeViewModel, or using the previous employee example, CreateEmployeeViewModel, EditEmployeeViewModel, etc. The idea is that the "ViewModel" emphasises the fact that we're dealing with presentation concerns, and disambiguates the ViewModels from any domain model objects that you may have.



回答5:

I've been using the term Envelope as part of my names, which I started using shortly before I read chapter 1 of the Wrox book and discovered the more commonly-accepted term is ViewModel.

However, these ViewEnvelopes that I create are only for very simple encapsulation when I have two or more (typically unrelated) strongly-typed models I'd like to hand to my View. They do not contain any other functionality---the envelope is intended only as delivery mechanism in this sense, whereas the term ViewModel, for me, seems less descriptive for how I'm using it, and also possibly more ambiguous as to what its real purpose is.

I might create, for example, a CustomerUpdateEnvelope class which exists solely to deliver a Customer object and an unrelated NewsTicker object, for example, to my Customer Update view.



回答6:

Rather late for this particular thread, but I've written a few slightly more detailed suggestions about ViewModel naming conventions in a blog post, which may be useful to others.