Basics of ASP.NET MVC


basics of mvc

ASP.NET MVC (Model View Controller) is a framework used to create web applications in the .NET platform. This framework is just an alternative to the widely used ASP.NET framework.

The model-view-controller is an architectural pattern designed to apply to the UI layer. The main purpose of this pattern is to make the UI(presentation layer) code loosely coupled i.e. many developers parallelly work on the same UI files(asp.net doesn't support such development with UI files .aspx, and .aspx.cs) without any dependency.

Let's learn the MVC framework in an easy Q & A model.
 

Model View Controller(MVC)

What is MVC Architectural Pattern?
Architectural pattern nothing but a layout(design/workflow) with specific rules to follow while implementation. As per this pattern, the MVC UI divided into three major components i.e. Model, View, and Controllers.

What is Model, View, and Controller in MVC UI?
The Model is a class to define properties to hold data.
The View is a UI, used to access the data from the model and present
The Controller is a class used to take the user's actions and call the right view to the user as per the model.

Steps to create an MVC project in Visual Studio?
Step 1: 
Open the Visual Studio 2019 or 2017
Step 2:
Select File -> New -> Project option from the menu
Step 3:
Select ASP.NET WebApplication(.NET Framework) template, click on create button
Step 4:
Select the MVC template from the options, click next
Now visual studio create and open the MVC project in the solution explorer

What is the default project folder structure for the MVC project in Visual Studio?
Below is the default project structure for MVC:
1. App_Start folder:
Contains files for configuration
2. Content folder:
Contains files for layout changes i.e. CSS files
3. Controllers folder:
Contains Controller class files
4. Fonts folder:
Contains regular system defined fonts files
5. Models folder:
A place to create model classes
6. Scripts folder:
Contains default javascript .js files
7. Views folder:
All View files(.chtml)
8. _ViewStart.chtml :
Common layout file for the project (equal to .master file in asp.net)
9. Global.asax:
Application extension file to track application and session events
10. Web.config:
Configuration for application

What is the base namespace for the MVC project?
"System.Web.Mvc" is the base namespace for MVC project implementation.

What are the types of configuration files in the MVC project?
We can find the below three configuration files in App_start folder by default:
1.BundleConfig.cs
2.FilterConfig.cs
3.RouteConfig.cs
BundleConfig:
Configuration file to define bundling for .CSS and .js files
Syntax:
public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {            
            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));
        }
    }
Definition: Bundling means grouping the files(scripts and content) together and provide as a bundle to compress. 
FilterConfig:
Configuration file to define any global application filters
Syntax:
public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }
    }
RouteConfig:
Configuration file to define the application Routings 
Syntax:
public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
Definition: Routing means mapping the URLs to Controller action methods.

What are the types of application filters in MVC?
Below is the list of filters supported by MVC:
1.Authorization filter
2.Action filters
3.Result filters
4.Exception filter
Authorization filter:
Filter used to authorize access to the controller or action methods
syntax:
[Authorize]
public ActionResult Index()
{
return View();
}
The Action and Result filters are custom filters. Use the below two filters to implement the same using the ActionFilterAtrribute class:
Action Filters:
1.OnActionExecuting
2.OnActionExecuted
Result Filters:
1.OnResultExecuting
2.OnResultExecuted
Exception filter:
filter used to handle the exception thrown by action methods
syntax:
[HandleError]
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
What are the types of view engines used in MVC?
MVC used the below two types of view engines to include the server-side code inside the view.
1. Razor View Engine
Razor is not a new language, it's a new markup syntax. Its a widely accepted syntax for mvc application because of simple to use and support for TDD.
All Razon syntax starts with '@' and the extension for razor files is '.cshtml' (or) '.vbhtml'
2. Webform View Engine
This is a default view engine and syntax similar to asp.net forms.

What is the role of an HTML helper in MVC?
HtmlHelper is a class used to generate the HTML elements in a view with the help of extension methods. 
for example:
 1. @Html.TextBox("txtBox","Hi")
The above HtmlHelper generates the below HTML element at runtime
<input type="text" id="txtBox" value="Hi"/>
2. @Html.AntiForgeryToken()
Here the yellow represents the HtmlHelper object, and blue represents an extension method from the HtmlHelper class.
Few other samples HtmlHelpers:
1.@Html.ActionLink()
2.@Html.TextArea()
3.@Html.Checkbox()
4.@Html.RadioButton()
5.@Html.Label()
etc..

What are the types of HTML helpers in MVC?
HtmlHelpers in MVC are three types:
1. Inline HtmlHelpers
Inline HtmlHelpers are implemented using the @helper tag.
2. Inbuilt HtmlHelpers
Again, Inbuilt HtmlHelpers are two types:
a. Standard Html Helpers
These HTML helpers used to create normal HTML elements.
for example:
@Html.TextBox("txtBox","Hi")
b. Strongly Typed Html Helpers
These Html helpers used to create the HTML elements based on the model properties. It also uses the lambda expressions for model binding.
for example:
@Html.TextBox(model => model.StudentId)
3. Custom HtmlHelpers
These custom helpers are extended from the HtmlHelper class.

What are the state management types in MVC?
In MVC, we have the below state management options:
1.ViewData
Used to transfer the data to the controller action method to view only. Need type casting in case of any complex type usage. It's a ViewDataDictionary and values stored in key/value pairs.
for example:
 public ActionResult Index()
        {
            ViewData["list"] = schoolContext.Teachers.ToList();  // type cast required in view
        }
2.ViewBag
Used to transfer the data to the controller action method to view only. No need for typecasting. It's a dynamic type.
for example:
public ActionResult Index()
        {
            
            ViewBag["vblist"] = schoolContext.Teachers.ToList(); // type cast not required in view
        }
3.TempData
Similar to view data. Used to transfer the data to the controller to controller, action to another action method and controller to view.
It's a TempDataDictionary and values stored in key/value pairs.
for example:
public ActionResult Index()
        {            
            TempData["tlist"] = schoolContext.Teachers.ToList(); // type case required in view
       }

Still, we can extend the lifetime of temp data using 'Keep() and 'Peek()' methods. Both are used to retain the data in the subsequent requests.
example:
TempData.Keep();  // two different calls
 TempData.Peek("emp"); // direct call
4.Session
Used to persist data between multiple requests without expiry.
for example:
public ActionResult Index()
        {            
            TempData["tlist"] = schoolContext.Teachers.ToList(); // type case required in view
       }
Conclusion

In this journal, I covered most of the basics to understand what is MVC and what are the main core concepts under it. I hope this is helpful for a quick start on MVC.



No comments:

Post a Comment