Tuesday, February 15, 2022

Introduction to MVC (Model-View-Controller) (Questions and Answers)

MVC (Model-View-Controller) (Interview Questions)

  • The Model-View-Controller (MVC) architectural pattern separates an app into three main components: Model, View, and Controller. The MVC pattern helps you create apps that are more testable and easier to update than traditional monolithic apps.
  • It supports separation of concern as Model describes data, View represents UI and Controller manages the presentation logic which handles user request.
  • Using the MVC pattern for websites, requests are routed to a Controller that is responsible for working with the Model to perform actions and/or retrieve data. The Controller chooses the View to display and provides it with the Model. The View renders the final page, based on the data in the Model.


Model (Application Data)

Create clean model classes and easily bind them to your database. Declaratively define validation rules, using C# attributes, which are applied on the client and server.
ASP.NET supports many database engines including SQLite, SQL Server, MySQL, PostgreSQL, DB2 and more, as well as non-relational stores such as MongoDB, Redis, and Azure Cosmos DB.

View (UI)

The Razor syntax provides a simple, clean, and lightweight way to render HTML content based on your view. Razor lets you render a page using C#, producing fully HTML5 compliant web pages.

Controller (User Request handling)

Classes that:
  • Handle browser requests.
  • Retrieve model data.
  • Call view templates that return a response.
Simply route requests to controller actions, implemented as normal C# methods. Data from the request path, query string, and request body are automatically bound to method parameters.


Return types of Controller Action Method

  • View Result
  • Content Result
  • ReDirect Result
  • JavaScript Result
  • JSON Result
Advantages of MVC
  • Multiple View Support
  • Change Accommodation
  • Separation of Concern
  • More Control
  • Testability
  • Lightweight

Session in MVC

ViewBag, ViewData, and TempData all are objects in ASP.NET MVC and these are used to pass the data in various scenarios.

  • TempData
TempData is a dictionary object to pass the data from one action to other action in the same Controller or different Controllers. Usually, TempData object will be stored in a session object. Tempdata is also required to typecast and for null checking before reading data from it. TempData scope is limited to the next request and if we want Tempdata to be available even further, we should use Keep and peek.
  • ViewData
ViewData is a dictionary object to pass the data from Controller to View where data is passed in the form of key-value pair. And typecasting is required to read the data in View if the data is complex and we need to ensure null check to avoid null exceptions. The scope of ViewData is similar to ViewBag and it is restricted to the current request and the value of ViewData will become null while redirecting.
  • ViewBag
ViewBag is a dynamic object to pass the data from Controller to View. And, this will pass the data as a property of object ViewBag. And we have no need to typecast to read the data or for null checking. The scope of ViewBag is permitted to the current request and the value of ViewBag will become null while redirecting.

ASP.NET MVC
It is web application framework.
It is lightweight and highly testable framework.

MVC Routing
Controller =>Action Method forms route.

It is a powerful URL-mapping component that lets you build applications that have comprehensible and searchable URLs. 

This enables you to define your application's URL naming patterns that work well for search engine optimization (SEO) and for link generation, without regard for how the files on your web server are organized. 

You can define your routes using a convenient route template syntax that supports route value constraints, defaults and optional values.

Convention-based routing enables you to globally define the URL formats that your application accepts and how each of those formats maps to a specific action method on a given controller. 

When an incoming request is received, the routing engine parses the URL and matches it to one of the defined URL formats, and then calls the associated controller's action method.

Attribute routing enables you to specify routing information by decorating your controllers and actions with attributes that define your application's routes. This means that your route definitions are placed next to the controller and action with which they're associated.



MVC Filters
Action Filters are attributes which we can apply to action methods.
Action Filters are also logic which we can execute before or after Action Method.

Partial View in MVC
It is a chunk of HTML that can be inserted into an existing DOM.
It is used to componentize Razor view.

Page Life Cycle of MVC
  • App Initialization
  • Routing
  • Instantiate and Execute controller
  • Locate and Invoke controller
  • Instantiate and Render the view
View Model in MVC
It is a plain class with properties, which is used to bind it to a strongly typed view.
View Model can have the validation rules defined for its properties using data annotations.

Database first approach in MVC using Entity Framework
It is an alternative to Code first approach.
The Entity Data Model creates model codes(Classes, properties, DbContext, etc.) from the database in project. The class behalves as the link between database and controller.

MVC Scaffolding
Scaffolding is a code generation framework for ASP.NET web applications.
Visual Studio includes pre-installed code generators for MVC and Web API projects.

Razor in ASP.NET MVC
It is a View Engine which is pluggable module that implements different template syntax options.

Default route in ASP.NET MVC
URL : "{controller} / {action} / {id}"

GET and POST action types
GET
It is used to request data from a specified resource.
POST
It is used to submit data to be processed to a specified resource.

View Data VS View Bag
Both are used to pass data from controller to view.
Both are available for current request only.
View Data requires type casting for complex data type and checks for null values to avoid error.
View Bag doesn't requires typecasting for complex data type.
In both, if redirection occurs then their values become null.

Benefits of Area in MVC
It allows us to organize models, views and controllers into separate functional sections of the application, such as administration, billing, customer support and many more.
It is easy to integrate with other areas.
It is easy for unit testing.

Filters execution order
Authorization Filters
Action Filters
Result Filters
Exception filters are executed in the end.

Add constraints to the route
Using Regular Expression
Using object that implements IRoute Interface

Validation in MVC
Using validators defined in System.ComponentModel.DataAnnotations namespace.
Types of validators
[Required]
[DataType]
[Range]
[StringLength]

Instances where Routing is not required
Physical file has matching URL
Routing is disabled

Implement Ajax in MVC
Using Ajax library
Using JQuery

Peek and Keep in Temp Data
When TempData is read in the current request, its no longer available in subsequent requests. If we want to keep it for subsequent requests, we need to call keep method after reading TempData.

@TempData["Data"];
TempData.Keep("Data");
        OR
string str = TempData.Peek("Data").ToString();

Peek is alternative to keep but it reduces the code. It reads data as well as keeps it for subsequent requests.

WebAPI
It is a technology by which we can expose data over HTTP following REST principles.
It allows us to send data to multiple devices like laptop, mobile phones, smart watches etc.

Main Razor syntax
Razor code blocks are enclosed in @{...}
Inline expressions start with @
Code statements end with semicolon
Variables are declared with var keyword
Strings are enclosed with quotes
File ends with .cshtml extension

Forms Authentication in MVC
Authentication is giving access to the user for a specific service by verifying his identity using his credentials like username and password. Sometimes resources are issued to users based in their roles.

Render Body and Render Page
Renderbody() exists in layout page and it will render the child pages / views.
Renderpage() also exists in layout page and multiple Renderpage() can be there.














No comments:

Post a Comment

Thanks for showing your interest
I will shortly get back to you