| by Achyut Kendre | No comments

What is MVC? How to use ASP.NET Core?

ASP.NET Core 3.1
MVC in ASP.NT Core

Example : https://drive.google.com/file/d/12vVMoD8pX9SOmKiwcmVzqkChh9D6WcDw/view?usp=sharing

ASP.NET Core support MVC design pattern where M stands for Model, V is called View & C stands for Controller i.e. Model View Controller design pattern.

What is Design Pattern?

Design Pattern tells you to write a code so that you will get some kind of advantage. We have so many design pattern like MVC, MVP, MVVM, Repository Design Pattern, etc. every design pattern has it’s own advantages.

What is MVC Design Pattern?

MVC is called Model View Controller design pattern has only one principle that is called SOC (separation of concerns) , it means identify the basic concerns of any thing and separate it from each other then performance in terms of load, the load handling capability of application increases.

If you take example of any program weather it is addition of two programs or a big ERP software every program or software will have three basic things User Interface (UI) , Logic and Data. So when you implement MVC in any program MVC says separate data from logic and logic from user interface where data is managed by the Model, UI will be managed by the View and Logic will be managed by the Controller.

So indirectly we can say Model is responsible for Data, Logic is responsibility of Controller and View is responsible for generating User Interface.

How MVC Works in ASP.NET Core?

Basic working flow of the MVC in ASP.NET Core as follows –

Let us try to understand this –

Step 1: User open the browser and make the request to asp.net core mvc application by typing url in address bar.

Step 2: Request goes to route engine, route engine will resolve the request url and decided which action of which controller to be called and request is given to a action from the controller.

Step 3: Action will receive the request and start processing the request while processing request if it needs data it will talk to model that is optional , it will talk to model only when data is required.

Step 4: Model will create data or talk to database or any data source and make the data available to controller action.

Step 5: After processing action will communicate data to a view and view will create the presentation of data in UI.

Let us try to understand controller and routing in more detail –

What is Controller?

  • Controller is responsible for logic or interaction part of the application.
  • Controller is public class which will have suffix Controller which inherits from the built in class called Controller which contains set of methods called action.
  • Controller class should be public can not be abstract ,private.
  • Actions are the methods defined inside the controller class, should be public, can not be abstract, can not be static, public and overridden method.
  • Their will be one to one mapping between user interaction and action, every request in mvc maps to action from the controller.

What is routing and how URL routing works?

  • Routing is mechanism by which route engine decides which action of which controller to be selected to process the request.
  • By default ASP.NET Core support url routing, in url routing we create the url patterns and register those url patterns to a route table.
  • When user makes a request the requested url will be compared to the patterns from route table sequentially where their is match it will execute that route and call the specific action of specific controller.

How to User MVC in ASP.NET Core 2.x?

To use the MVC in ASP.NET Core 2.x we need to use following two services , to be registered to IoC container in configure method startup class.

  1. AddMvc()
  2. AddMvcCore()

What is difference between AddMvc() and AddMvcCore()?

AddMvcCore():=> this method only add the core MVC services/basic MVC service , indirectly we can say it will not add any support for view. .
AddMvc():=> method adds all/full fletch MVC services. internally calls AddMvcCoe.

ASP.Net core 3.x by default support End Point routing, so if you want to use above services you need to disable the end point routing since above services do not support the end point routing as follows –

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvcCore(p => p.EnableEndpointRouting = false);
        }
 public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(p => p.EnableEndpointRouting = false);
        }

Here EnableEndPointRouting will help you to enable or disable the endpoint routing..

After this you can use the url routing as follows.

How to Activate the Routing in ASP.NET Core 2.x ?

ASP.NET Core 2.x provides you following two middleware’s that is suppose to be injected in request pipe line those are –

  1. UseMvc()
  2. UseMvcWithDefaultRoute()

UseMvc will inject the middleware in request pipe line without any routing where as UseMvcWithDefaultRoute() will inject the mvc in request pipe line with default route and default route will have default action index and default controller will be Home.

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)         
  {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
           app.UseMvcWithDefaultRoute();
  }
 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc(
                rt =>
                {
                    rt.MapRoute("default", "{controller=Home}/{action=index}/{id?}/{str?}/{abc?}");
                }
             ); 
}

This says when you make request to ASP.NET Core application, by default it will take you to home controller to index action.

Now create the Controller and action and run the application using following steps –

Step 1: Create a class in controllers folder called HomeController

Step 2 : Define a methods called index which returns you string .

Step 3 : Run the application and you will get the home and index.

public class HomeController:Controller
    {
        public string Index()
        {
           return "Home Controller Index Action Called!";
        }
    }

Leave a Reply