View Model place in N Tier ASP .NET MVC application

1.6k views Asked by At

I have read this and was wondering about this.

My application contains 4 Layers

  1. Web Project / UI
  2. BLL
  3. DAL (contains EF)
  4. Entity Layer

I have placed VM in UI layer as of now and its a combination of different classes. something like this

    public class CompanyVMIndex
    {
       public CompanyVM Company { get; set; }
       public BillingAddressVM BillingAddress { get; set; }
       public List<ShippingAddressVM> ShippingAddress { get; set; }
       public List<CompanyContactVM> CompanyContact { get; set; }
    }

I am confuse now that how I can send this data from UI to BLL and then DAL. I have read by automapper but does it handle this situations, if yes then how? As of now, I have decided to move VMs to Entity Layer which will be connected to all the three layers so that I can send and receive data in the same, any other good idea?

This is how I pass data from UI to BLL

             public ActionResult Create(CompanyVMIndex companyVM)
             {
               if (ModelState.IsValid)
                  {
                     //Calling BLL here
                     BLLFunction(companyVM)

                   }

                    return View("Index");
            }

then in BLL and something similar in DAL with Automapper

    public int BLLfunction(CompanyVMIndex CompanyVM)
    {

    }

now, how I can pass data as BLL does not have the definition of CompanyVMIndex which is a VM and in Web UI

1

There are 1 answers

9
John Saunders On BEST ANSWER

If you want to be "pure", then the ViewModel (or, in general, whatever model you send to the view) will never be seen by your BLL or any other layer. It will only ever be used to communicate between controllers and views.

When it comes time to retrieve data from the BLL or send data back to the BLL, other classes would be used. Data would be copied to and from the ViewModel classes.

This way, the ViewModel contains precisely what the controllers need in order to communicate with the views, and exactly what the views need to communicate back to controllers. The BLL can be about business logic, and may use classes which do not exactly correspond to any ViewModel.

For example, a ViewModel may contain information about a customer and his company, and about the products the customer has ordered in the past 3 months. It may also contain other data to be used to create user interface elements in the view: for instance, a list of shipping methods. This data almost certainly comes from several different BLL classes and methods. The shape of this data is oriented towards communication between the view and the controller. The BLL classes are oriented towards business logic and possibly the database.