ASP.NET Core MVC

MVC consists of three fundamental parts - ModelView and Controller. It's an architectural design pattern for implementing User Interface Layer of an application. A typical real-world application usually has the following layers.
  • User Interface Layer
  • Business Logic Layer or Domain Layer
  • Data Access layer
MVC design pattern is usually used for implementing the User Interface Layer of the application.

what is mvc

  • MVC is an architectural design pattern for implementing User Interface Layer of an application
  • Model : Set of classes that represent data + the logic to manage that data. Example - Emplopyee class that represents the Employee data + EmployeeRepository class that saves and retrieves employee data from the underlying data source such as a Database.
  • View : Contains the display logic to present the Model data provided to it by the Controller
  • Controller : Handles the http request, work with the model, and selects a view to render that model.
Iin the MVC design pattern we have a clear separation of concerns, each component has a very specific task to do.


Setup MVC in ASP.NET Core Application

Step 1: In ConfigureServices() method of the Startup class in Startup.cs file, include the following line. This line of code adds the required MVC services to the dependency injection container in asp.net core.

services.AddMvc();

Step 2 : In the Configure() method, add UseMvcWithDefaultRoute() midddleware to our application's request processing pipeline. Modify the code as shown below.

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

    app.UseStaticFiles();

    app.UseMvcWithDefaultRoute();
  
}

Because of middleware order here if the request is an MVC request, UseStaticFiles() middleware will pass that request to UseMvcWithDefaultRoute() middleware which will handle the request and produces the response.


Difference between AddMvc() and AddMvcCore() methods. 

AddMvcCore() method only adds the core MVC services. On the other hand, AddMvc() method adds all the required MVC services. AddMvc() method calls AddMvcCore() method internally, to add all the core MVC services. 

Please note : To be able to return data in XML format, we have to add Xml Serializer Formatter by calling AddXmlSerializerFormatters() method in ConfigureServices() method in Startup.cs file.


In ASP.NET Core MVC, there are 3 ways to pass data from a controller to a view

  1. Using ViewData- ViewData is a dictionary of weakly typed objects. does not provide compile-time type checking and as a result, we do not get IntelliSense
  2. Using ViewBag- ViewBag is a wrapper around ViewData. With ViewBag we use dynamic properties to store and retrieve data. Casting is not required.
  3. Using a strongly typed model object. This is also called a Strongly typed view - provides compile-time type checking and IntelliSense

Setting the Layout for MVC Application using _ViewStart.cshtml

By setting the Layout property in _ViewStart.cshtml file maintaining our application becomes easier. This file is hierarchical we can also place it in any sub-folder in the Views folder. The layout page specified in the ViewStart file in the Home sub-folder overwrites the layout page specified in the ViewStart file in the Views folder.
If need to use a layout file that is different from what is specified in _ViewStart.cshtml, you can do so by setting the Layout property in an individual view.



_ViewImports cshtml in ASP NET Core MVC

_ViewImports.cshtml file is usually placed in the Views folder. It is used to include the common namespaces so we do not have to include them in every view that needs those namespaces. 
The settings specified in the _ViewImports file in the Home sub-folder overwrites the settings specified in the _ViewImports file in the Views folder. 

@using directive is used to include the common namespaces. In addition to @using directive, _ViewImports file also supports the following directives.

addTagHelper
removeTagHelper
tagHelperPrefix
model
inherits
inject



Routing in ASP.NET Core MVC

There are 2 routing techniques in ASP.NET Core MVC Conventional Routing and Attribute Routing

Conventional Routing:-
The following is the code in the Configure() method in Startup.cs file.

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

    app.UseStaticFiles();

    app.UseMvcWithDefaultRoute();
}

UseMvcWithDefaultRoute() extension method adds MVC with the following default route to our application's request processing pipeline. UseMvcWithDefaultRoute() method internally calls UseMvc() method and it sets up the default route. 

If you want to define your own route templates and want to have more control over the routes, use UseMvc() method, instead of UseMvcWithDefaultRoute() method.

app.UseMvc(routes =>
{
    routes.MapRoute("default""{controller=Home}/{action=Index}/{id?}");
});


Attribute Routing:-  

public class HomeController : Controller
{
    [Route("Home/Details/{id}")]
    public ViewResult Details(int id)
    {        
        return View();
    }
}



Comments