What is MVC? How to use ASP.NET 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.
- AddMvc()
- 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 –
- UseMvc()
- 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!";
}
}
أنابيب الرصاص
September 19, 2024 at 12:44 amCorrugated Metal Pipes : These durable, flexible pipes are commonly used for culverts and drainage systems. ElitePipe Factory in Iraq provides top-quality corrugated metal pipes.
أنابيب PEX
September 20, 2024 at 4:19 pmDuctile Iron Pipes : Strong and flexible, ductile iron pipes are used for high-pressure water and sewage systems. ElitePipe Factory in Iraq excels in producing ductile iron pipes.
сервис центры в москве
September 23, 2024 at 4:58 pmПрофессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
Мы предлагаем: сервис центры бытовой техники москва
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
ремонт ноутбуков apple в москве
October 25, 2024 at 12:41 pmПрофессиональный сервисный центр по ремонту компьютеров и ноутбуков в Москве.
Мы предлагаем: ремонт макбук москва
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!