For reasons given below, strongly typing the layout seems a logical approach.
But I am scared to ignore the warnings of so many programmers so much more skilled an experienced than myself.
Why do so many recommend avoiding this approach?
Brief Breakdown of Arguments For / Against
I am planning to use a model like this as a base class for my application's ViewModels.
public class LayoutViewModel
{
public string CanonicalURL { get; set; }
public string PageTitle { get; set; }
public string MetaTitle { get; set; }
public string Description { get; set; }
public string OGImage { get; set; }
public string OGType { get; set; }
}
This question generated some sensible sounding arguments against doing so, for example:
"layout is a partial used by all of your views. Specifying a model
there would add restriction to every view on your site to also have
that model."
"you are avoiding one "bad practice" (dynamic typing of ViewBag), but
trying to replace it with another bad practice (tying your layout to
model data). Layouts should not rely on data.."
Ant P suggested: "You should delegate the parts of your layout that
"need a model" to a separate controller using partial views and
RenderAction"
But on reflection, I don't find them convincing:
PageTitle, MetaTitle, Description and OG data are required for
every full page view, so I feel it's proper that the ViewModel should contain
that data.
Why should I avoid "tying my layout to model data"? Is not every MVC view tied to the model it is based on?
ViewBag is inconvenient and error prone
The only disadvantage I see is that layout changes may require changes to the base model also. But this seems minor compared to the advantages a strongly typed _layout.cshtml. And realistically, it's unlikely that the properties above will change any time soon.
I am building an ASP.Net MVC application using a ViewModel approach to keep my domain entities separate from the "models" used by my UI. I am using the following convention for naming my ViewModel classes. ViewModelName = ViewName + "ViewModel". For example:
Index + ViewModel = IndexViewModel
So far, so good, this is a fairly common pattern and there is a lot of guidance on this topic on StackOverflow and elsewhere. My question concerns child objects used by my ViewModels. If my ViewModel requires a class with properties identical to my a domain model object, I simply include the domain model within my ViewModel. For example:
public class PersonViewModel
{
public int PersonID { get; set; }
public Address Address { get; set; }
public string SomeOtherProperty { get; set; }
}
However, I am not sure what naming convention to use when I need a child object with different properties from my domain model. For example if Address needed a few additional properties besides what is in the Address domain model, what should I call it? I considered AddressViewModel like so:
public class PersonViewModel
{
public int PersonID { get; set; }
public AddressViewModel Address { get; set; }
public string SomeOtherProperty { get; set; }
}
but that just doesn't feel right to me. My gut instinct is that the ViewModel suffix should only be for the top level ViewModel.
I am looking for suggestions from other developers on what naming conventions they use in this scenario, specifically what would you call the child object in this case?
I'm going to put an answer on this just because no one else has! (I know I'm a little late to this party!)
I've pondered over this exact thing many times and tried different conventions over the years. The one thing I picked up on is that you are using a naming convention...
If your naming convention is to suffix your UI model classes with 'ViewModel' then the child models should have the same suffix otherwise you're breaking your own convention!
Also lets say you have an Address table (or whatever you have) and a Customer can have an address and a Company has an address and they both use the same table, then you may use the same child model for both parent models. It seems right to have an AddressViewModel. One day you might have a View/PartialView and it's model is IEnumerable<AddressViewModel>
I know there's no real right answer to this, but this is my answer :-)
I have a details view that is typed to IEnumerable. The view with a bunch of drop downs that let you add filters to the list of records rendered.
All these dropdowns correspond to properties on the MVC model:
public class Record
{
public string CustomerNumber { get; set; }
public string CustomerName { get; set; }
public string LineOfBusiness{ get; set; }
public DateTime? Date { get; set; }
}
Now, I'm using my model as my dto to shuffle data between my controller and my repo. Since all my drop down filters represent the model properties, I pass my model to a repo retrieval method, check its properties and filter based on its values? In other words:
public IEnumerable<TradeSpendRecord> Get(TradeSpendRecord record)
{
IQueryable<tblTradeSpend> query = _context.tblRecords;
if (!String.IsNullOrEmpty(record.CustomerName))
query = query.Where(x => x.CustomerNumber == record.CustomerNumber);
if (!String.IsNullOrEmpty(record.LineOfBusiness))
query = query.Where(r => r.LOB == record.LineOfBusiness);
SNIP
Hope this isn't too subjective, but I'm wondering if anyone has any input about whether this is a good/bad practice. I haven't seen a whole lot of examples of dynamic filtering like I need to do, and am looking for some guidance.
Thanks,
Chris
If you're doing what I think you're doing, I'm not sure this is the best way of doing it.
Keep your 'Models' in your MVC/presentation layer (whether this is one physical assembly or not) dedicated to your presentation layer. The only things that should be touching them are your Views and your Controllers. You don't want what should be independent entities to be so tightly coupled to your View Models.
I'd suggest creating a separate TradeSpendFilter class, which, at its simplest, exposes the filterable properties of your domain entity (likely more than any given View Model). You'd then pass this into your "filtering service" or whatever it may be. This also means you can extend your filtering functionality independent of both your domain models and your MVC app. For example, if you suddenly want to filter multiple objects, you can simply change...
public class TradeSpendFilter
{
public string CustomerName { get; set; }
...
}
...to...
public class TradeSpendFilter
{
public IEnumerable<string> CustomerNames { get; set; }
...
}
... without causing all sorts of problems for your MVC app.
Additionally, it will also mean you can make use of your filtering functionality elsewhere, without tying further components to your MVC app and ending up in a bootstrapped mess.
I read this q/a Real example of TryUpdateModel, ASP .NET MVC 3 and was really interested on #ben-foster response.
I started doing a comment on that answer but got quite long, so started a new Question.
Having ViewModels for everything approach (which i like a lot) get me into some 'weird scenarios' that i want advice in how should I do.
Imagine this structure :
public class ProductListEditableViewModel {
List<ProductEditViewModel> products {get;set;}
}
public class ProductEditViewModel {
List<PriceViewModel> prices {get;set;}
}
public class PriceViewModel {
CurrencyViewModel currency {get;set;}
}
and so on ... ? do you really make one view model for each inner class? how then you map all that to the Model Object?
Also, that covers the Edit, but I have an Add, a send via email, and potentially more Views so more ViewModels!! should i end like something :
AddCurrencyViewModel
QuickAddCurrencyViewModel
EditCurrencyViewModel
ListCurrencyViewModel
DeleteCurrencyViewModel
ShareCurrencyViewModel
all having the 'almost same' properties ?
Should all those be packed into one file ?
Also do i need all this all viewModels or a inheritance approach might be better?
If you can, I´ll appreciate elaborate on complex scenarios
Also, I use a DTO approach to expose some of the model objects into web service / apis, so I already have some form of mapping already in place where this DTO are not exactly my ViewModels, should I remove one of them? what´s the suggestion in this scenario ?
I´m using entity framework but i think the question is (or should be) ORM agnostic.
Not using UoW pattern (will this helps?) as looks it´s gets more complicated as the depth of the object increases.
Thanks a lot!
We typically have a view model per view so yes, if you have lots of views you will have lots of view models.
In typical CRUD applications we often have very similar views, for example Add and Update. In these cases, yes we use inheritance rather than writing duplicate code - usually Add subclasses Update.
public class AddFoo : UpdateFoo {
public AddFoo() {
// set up defaults for new Foo
}
}
public class UpdateFoo {
public string Name { get; set; }
// etc.
}
We attempted to "share" view models between views in the past and normally ended up in a world of pain.
With regard to your "weird scenario" - this does look weird indeed, but perhaps because I don't understand your application.
The goal of your view model is to provide the information to the view that is needed and ideally to flatten any complex objects so they are easier to work with. You shouldn't split your view models up like your example unless it makes sense to do so.
Let's say I wanted to a create a view where the customer could change their contact details. Taking the following domain object:
public class Customer {
public string FirstName { get; set; }
public string LastName { get;set; }
public Address Address { get; set; }
}
I'd probably flatten this to a view model like so:
public class UpdateAddressModel {
public string FirstName { get; set; }
public string LastName { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string AddressCity { get; set; }
// etc.
}
Of course there will be occasions where it doesn't make sense to do this, for example a dashboard view in an online store where you have a list of products going out of stock and a list of recent orders - these two things are unrelated but are required by your view:
public class DashboardModel {
public List<Product> ProductsGoingOutOfStock { get; set; }
public List<Order> NewOrders { get; set; }
}
how then you map all that to the Model Object?
I'm assuming by Model Object you mean your data/domain model. The key takeaway here is that the view model you use to render your view is unlikely to be the same as the "models" you POST to the server and if they are, you're probably over-POSTing or you have some crazy enter-everything data capture screen that will make your eyes bleed.
I find it helps to think of what you send to your server as Commands and what you use to render your views as view models.
So the answer to your question - how do you map your complex view model to your data model? - Quite simply, you don't. You should send commands to the server that perform a specific task e.g. updating an address.
There's no hard and fast rule in how you structure your view models but generally go with what makes sense and if it starts to feel too complicated you're probably trying to do too much with one view.
I hope this helps. You'll find lots of posts relating to this matter on my blog.
I realize this is an old-ish question but I did want to address one of the questions posed by the OP that was not answered.
Should all those [ViewModels] be packed into one file ?
Most of the examples I see put each ViewModel in a separate file, so the dominant convention seems to be one file per viewmodel, but I found in practice that this seems to be overkill. Instead I put all viewmodels for a particular controller in one file with multiple viewmodels in it. So for example if User is my Controller and I have several viewmodels associated with this controller such as UserAddViewModel, UserEditViewModel, UserDeleteViewModel I put all of the viewmodels for User in one file called UserViewModels.cs
I have a standard Domain Layer entity:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set;}
}
which has some kind of validation attributes applied:
public class Product
{
public int Id { get; set; }
[NotEmpty, NotShorterThan10Characters, NotLongerThan100Characters]
public string Name { get; set; }
[NotLessThan0]
public decimal Price { get; set;}
}
As you can see, I have made up these attributes completely. Which validation framework (NHibernate Validator, DataAnnotations, ValidationApplicationBlock, Castle Validator, etc) in use here is not important.
In my client layer, I also have a standard setup where I don't use the Domain entities themselves, but instead map them to ViewModels (aka DTO) which my view layer uses:
public class ProductViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set;}
}
Let's then say that I want my client/view to be able to perform some basic property-level validations.
The only way I see I can do this is to repeat the validation definitions in the ViewModel object:
public class ProductViewModel
{
public int Id { get; set; }
// validation attributes copied from Domain entity
[NotEmpty, NotShorterThan10Characters, NotLongerThan100Characters]
public string Name { get; set; }
// validation attributes copied from Domain entity
[NotLessThan0]
public decimal Price { get; set;}
}
This is clearly not satisfactory, as I have now repeated business logic (property-level validation) in the ViewModel (DTO) layer.
So what can be done?
Assuming that I use an automation tool like AutoMapper to map my Domain entities to my ViewModel DTOs, wouldn't it also be cool to somehow transfer the validation logic for the mapped properties to the ViewModel as well?
The questions are:
1) Is this a good idea?
2) If so, can it be done? If not, what are the alternatives, if any?
Thank you in advance for any input!
If you're using something supporting DataAnnotations, you should be able to use a metadata class to contain your validation attributes:
public class ProductMetadata
{
[NotEmpty, NotShorterThan10Characters, NotLongerThan100Characters]
public string Name { get; set; }
[NotLessThan0]
public decimal Price { get; set;}
}
and add it in the MetadataTypeAttribute on both the domain entity & DTO:
[MetadataType(typeof(ProductMetadata))]
public class Product
and
[MetadataType(typeof(ProductMetadata))]
public class ProductViewModel
This won't work out of the box with all validators - you may need to extend your validation framework of choice to implement a similar approach.
The purpose of validation is to ensure that data coming into your application meets certain criteria, with that in mind, the only place it makes sense to validate property constraints, like those you have identified here, is at the point where you accept data from an untrusted source ( i.e. the user ).
You can use something like the "money pattern" to elevate validation into your domain type system and use these domain types in the view model where it makes sense. If you have more complex validation (i.e. you are expressing business rules that require greater knowledge than that expressed in a single property), these belong in methods on the domain model that apply the changes.
In short, put data validation attributes on your view models and leave them off your domain models.
Why not use an interface to express your intent? Eg:
public interface IProductValidationAttributes {
[NotEmpty, NotShorterThan10Characters, NotLongerThan100Characters]
string Name { get; set; }
[NotLessThan0]
decimal Price { get; set;}
}
It turns out that AutoMapper may be able to do this for us automagically, which is the best case scenario.
AutoMapper-users: Transfer validation attributes to the viewmodel?
http://groups.google.com/group/automapper-users/browse_thread/thread/efa1d551e498311c/db4e7f6c93a77302?lnk=gst&q=validation#db4e7f6c93a77302
I haven't got around to trying out the proposed solutions there, but intend to shortly.
If you use hand-written domain entities, why not put your domain entities in their own assembly and use that same assembly both on the client and server. You can reuse the same validations.
I've been considering this as well for a while now. I totally understand Brad's reply. However, let's assume I want to use another validation framework that is suitable for annotating both domain entities and view models.
The only solution I can come up with on paper that still works with attributes would be to create another attribute that "points" to a domain entity's property that you are mirroring in your view model. Here's an example:
// In UI as a view model.
public class UserRegistration {
[ValidationDependency<Person>(x => x.FirstName)]
public string FirstName { get; set; }
[ValidationDependency<Person>(x => x.LastName)]
public string LastName { get; set; }
[ValidationDependency<Membership>(x => x.Username)]
public string Username { get; set; }
[ValidationDependency<Membership>(x => x.Password)]
public string Password { get; set; }
}
A framework like xVal could possibly be extended to handle this new attribute and run the validation attributes on the dependency class' property, but with your view model's property value. I just haven't had time to flesh this out more.
Any thoughts?
First of all, there is no notion of "standard" domain entity. For me, standard domain entity does not have any setters to begin with. If you take that approach, you can have more meaningful api, that actually conveys something about your domain. So, you can have application service that processes your DTO, creates commands that you can execute directly against you domain objects, like SetContactInfo, ChangePrice etc. Each one of these can raise ValidationException, which in turn you can collect in your service and present to the user. You can still leave your attributes on the properties of dto for simple attribute/property level validation. For anything else, consult your domain. And even if this is CRUD application, i would avoid exposing my domain entities to presentation layer.
Disclaimer: I know this is an old discussion, but it was closest to what I was looking for: Keeping DRY by reusing validation attributes. I hope it is not too far from the original question.
In my situation I wanted to make error messages availible in .NET views and in other viewmodels. Our entities have little to no business logic and are mainly targeted for data storage. Instead we have a large viewmodel with validation and business logic were I want to reuse error messages. Since the users are only conserned with error messages, I find this to be relevant as that is what is important to maintain easily.
I could not find a feasible way to remove logic from the partial ViewModels, but I found a way to convey the same ErrorMessage, such that it can be maintained from a single point. Since ErrorMessages are tied to the view, it can just as well be part of the ViewModel. Consts are considered static members, so defining the error messages as public string constants, we can access them outside the class.
public class LargeViewModel
{
public const string TopicIdsErrorMessage = "My error message";
[Required(ErrorMessage = TopicIdsErrorMessage)]
[MinimumCount(1, ErrorMessage = TopicIdsErrorMessage)]
[WithValidIndex(ErrorMessage = TopicIdsErrorMessage)]
public List<int> TopicIds { get; set; }
}
public class PartialViewModel
{
[Required(ErrorMessage = LargeViewModel.TopicIdsErrorMessage]
public List<int> TopicIds { get; set; }
}
In our project we were using custom html for dropdownlists, such that we could not use #Html.EditorFor helper in razor, thus we could not use unobtrusive validation. With the error message availible we could now apply the necessary attributes:
#(Html.Kendo().DropDownList()
.Name("TopicIds")
.HtmlAttributes(new {
#class = "form-control",
data_val = "true",
data_val_required = SupervisionViewModel.TopicIdsErrorMessage
})
)
Warning: You might need to recompile all related projects that rely on const values...