Home > DeveloperSection > Forums > How to implement n-layer architecture in MVC?
Jayden Bell
Jayden Bell

Total Post:105

Points:739
Posted on    January-07-2015 10:24 PM

 C# ASP.Net  ASP.NET MVC 
Ratings:


 1 Reply(s)
 780  View(s)
Rate this:

I know this question has been asked before. I am only asking so that I can get a better explanation. In my webforms applications, this is how I implemented my projects. The solution had two projects. The first project contains Data Access and Business Logic. The first project is referenced in the second project. The aspx.cs files call the business logic class and the business logic class calls the data access class.

I am trying to follow the same approach in my MVC applicaiton. How would I implement that? Controller calls Model which in turn calls Business logic? This approach would add overhead right?



Simons Hood
Simons Hood

Total Post:70

Points:494
Posted on    January-08-2015 2:52 AM

In reference to the direction the comments are taking this thread (this doesn't fit neatly into a comment):

The models folder that is created with a new MVC project is for View Models - they are classes to support views. These are not your business models or data models.

For instance, in a ViewModel that supports a view, you might have a enum property that renders to a dropdown:

public enum CustomerTypes

{

    INDIVIDUAL = 0,

    COMPANY

}

 

public class CustomerViewModel

{

    public CustomerTypes Type { get; set; }

 

    public string[] CustomerTypesSelectList { get; set; }

}

 

 

public class CustomerController : Controller

{

    public ActionResult Edit()

    {

        var model = new CustomerViewModel();

        model.CustomerTypesSelectList =

            Enum.GetNames(typeof(CustomerTypesSelectList));

 

        return View(model);

    }

}

And with this you have some javascript in your view to populate a fancy drop down list with the items in CustomerTypesSelectList.

The UI-specific string[] property is a common construct of a ViewModel that gets stripped away when it gets converted to the business model or data model. The Controller would control the conversion (a.k.a. mapping), but probably rely on another class to implement the mapping that ties together the ViewModel and the business model.

To sum up, in an n-layer architecture:

  1. The MVC Controller is not your business logic. Your business logic resides inside of various services and components that are called by the controller.
  2. The Models folder contains ViewModels - classes that are meant to support the operation of the UI only.
  3. The Controller calls a mapper to translate between ViewModels and business models when calling into the business layer.

 


Don't want to miss updates? Please click the below button!

Follow MindStick