MVC Pattern

MVC Pattern , ANGULAR WITH CORE .NET AND MVC RAZOR ENGINE

                                                 Introduction

This chapter will focus on the implementation of the MVC pattern within ASP.NET Core,
specifically from an API perspective as a fully functional web framework. We will explore
how data are mapped from HTTP requests and bound to action parameters and strongly
typed models, as well as how these models are validated before any data processing
happens.

At the end of this chapter, we will also have a broader understanding of how controllers
work and grasp the importance of action methods to handle incoming requests. We will
learn all about filters and how they can help by executing code before and after the
processing of requests in the pipeline.

Returning the appropriate responses is crucial in APIs, and formatting these
responses is essential when dealing with many different types of responses. In this
chapter, we will also look at how content negotiation uses formatters to return data in
specific formats for specific requests and how we can create custom response formatters
for serving particular responses.

The last section will briefly cover application parts, a new concept in ASP.NET Core
that allows applications to be much more modular than before by discovering MVC
components from within the application context or external assemblies.

MVC Pattern

Model View Controller (MVC) is a software design pattern for implementing web
applications with user interfaces, and it is used to separate the concerns of three major
components, which are models, views, and controllers. This architectural pattern has
been around for many years, and it strives to promote code reuse and simultaneous
development.

Controllers are the main entry point and handle requests initiated from user
interaction. Logic is performed from within the controller, and then it potentially creates
a model, which houses the state of the application and the business logic around it.
The model is then passed by the controller to a view, which has the responsibility of
rendering a user interface, possibly containing the data from the model.


Below Image shows communication between the controller model and view

MVC in ASP.NET Core

ASP.NET Core MVC is an application framework built on top of ASP.NET Core that allows us to make dynamic web applications with a clean separation of concerns. Compared to its predecessor, ASP.NET MVC (version 1 to 5), the new ASP.NET Core MVC version is open source, lightweight, and redesigned from the ground up to be faster and smaller than before. Its design gives us control entirely over markup and promotes testability within our applications.

When we look at the previous version of ASP.NET, two of the application models
it contains are MVC and Web API. The MVC application model was initially intended
for rendering views and is used in interactive web applications, whereas Web API was
designed to provide data responses, mainly as XML and JSON formats that are used in
web APIs.


Difference between components in MVC 5.x and Web API 2.x in the earlier versions of ASP.NET.


Below is the example of Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace My_First_API
{
    public class HomeController : Controller
    {
        public IActionResult Index()  /// Action Method
        {
            return View();
        }
    }
}

And suppose there are some situations where you want to treat your controller as normal POCO class then we can below decorator 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace My_First_API
{
 
   [NonController]
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}

Model Binding and Validation

In ASP.NET Core MVC, incoming requests are mapped to parameters of action methods,
which can be simple types like integers and strings or more complex types like complete
data transfer objects (DTOs). This process of binding HTTP requests to method
parameters is called model binding and abstracts away the mapping logic to prevent
rewriting the same map over and over.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace My_First_API
{
    [Route("api/{controller}/Home/{action}")]   // Routing 
    public class HomeController : Controller
    {
        [HttpGet("Welcome")]
        public IActionResult Index(string name,string contactNo)   // Input Parameter
        {
            return View();
        }
    }
}

Below piece of code shows an example of model binding

Note: I have developed a model in the controller itself, but we should create Model class separate from the controller


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace My_First_API
{
    [Route("api/{controller}/Home/{action}")]   // Routing 
    public class HomeController : Controller
    {
        [HttpGet("Welcome")]
        public IActionResult Index(string name,string contactNo)   // Input Parameter
        {
            return View();
        }
        [HttpPost("AddStudentRecord")]
        public IActionResult Student(Student student)   //  Model Binding
        {
            return View();
        }
    }

    // Below POCO class is an example of Model
    public class Student
    {
        [Key]
        public int Id { get; set; }
        [Required(AllowEmptyStrings = false, ErrorMessage = "Student name required")]
        public string studentName { get; set; }
        [Required(AllowEmptyStrings = false, ErrorMessage = "Student address required")]
        public string studentAddress { get; set; }
        [Required(AllowEmptyStrings = false, ErrorMessage = "Student grade required")]
        public string studentGrade { get; set; }
    }
}


Conclusion

This chapter pretty much sums up ASP.NET Core MVC from an API perspective, and
although there is far more to learn about this excellent framework, we will move on to
the next chapter, where we will be discussing the configuration model of ASP.NET Core.

With ❤️ Happy Coding

Comments

Popular posts from this blog

How to disable table row in Angular

How to create XML file dynamically in c#.net?

How to get Array value in Angular ?