Question

I have an MVC 4 project where the UI is strongly typed to a ViewModel. The view has certain elements that need to be shown in certain scenarios. These scenarios are governed by business logic so I don’t want to have some conditional statement like this in the UI

If (Role.Equals(“Admin”))
{
  <a href=””> Admin Link here</a>
}

What I have is the business layer create a view model for me. So the above statement is now in the business layer as below

If (Role.Equals(“Admin”))
{
 ViewModelClassObject.ShowAdminLinks = true;
}

And in my UI .aspx layer as below

If (model.ShowAdminLinks)
{
  <a href=””> Admin Link here</a>
}

Now the problem is this, I have the viewmodel classes in a separate class library which is referenced by both the business and web UI layer. Since the viewmodel class also has properties which map to the UI layer’s textboxes where I perform some validations like, the required field validator, Compare, Range validator, I now need to make a reference to the System.web.mvc layer in my ViewModel class library. Is this bad coding practice? Although the code compiles and builds I get the feeling that I am probably doing something that could possibly be a code smell. Alternatively, I am also considering moving the ViewModel classes back into the Web UI layer and using some sort of a viewmodel builder in the web project to create the view model by calling the business layers methods. This way there will be no need to have a separate ViewModel class library that references the System.Web.MVC dll and my controller can just call this View model builder class to build the view model

What are your thoughts on this?

Was it helpful?

Solution

I would separate ViewModels used by web project and DTO's used by business layer.

The reason is that probably you don't need property ShowAdminLinks or some dropdown values in business layer. So business layer knows only about the data it needs to know.

This way you get yourself clean multi-tier application. Of course it means you got to do a bit more coding with creating and setting DTOs values. Some use automapper for that, but i prefer not to. Why? It's not too hard to do it manually and better yet - no magic.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top