0% found this document useful (0 votes)
6 views

MVC Basics Training Material

Uploaded by

Skb Vignesh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

MVC Basics Training Material

Uploaded by

Skb Vignesh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 48

MSC TECHNICAL BASICS

OVERVIEW MVC BASICS


CONTENTS
 MVC Life Cycle
 Model
 View
 Controller
 MVC Session
 Html Helpers
 Partial Views (Action, Render Action, Partial & Render Partial)
 Role of Layout and View Start
 Model Binding
 Razor
 Role of Global.asax.cs
 Filters(Authorization, Exception, Action )
 Route (Conventional, Attribute)
 Bundle & Minification
 Type of Action Result
 Validation
 Area
 config files

Sensitivity: Internal
INTRODUCTION TO MVC

 ASP.NET MVC
ASP.NET MVC is a web framework based on Model-View-Controller (MVC) architecture. We can build dynamic
web applications using ASP.NET MVC framework that enables a clean separation of concerns, fast development,
and TDD friendly.
 ASP.NET MVC Versions

Sensitivity: Internal
Model: Model represents the shape of the data. A
class in C# is used to describe a model. Model
objects store data retrieved from the database

View: View is a user interface. View display model data to the


user and enables them to modify. View in ASP.NET MVC is HTML,
CSS, and some special syntax (Razor syntax) that makes it easy
to communicate with the model and the controller.

Controller: The controller handles the user


request. Typically, the user uses the view and
raises an HTTP request, which will be handled by
the controller. The controller processes the request
and returns the appropriate view as a response.

Sensitivity: Internal
MVC Lifecycle

 when a user enters a URL in the browser, it


goes to the webserver and routed to a
controller. A controller executes related view
and models for that request and create the
response and sends it back to the browser

Sensitivity: Internal
HOW TO CREATE MVC PROJECT IN VISUAL
STUDIO

Open Visual Studio ----> File ---> New Project

Sensitivity: Internal
HOW TO CREATE MVC PROJECT IN VISUAL
STUDIO

MVC folder structure


Sensitivity: Internal
MVC – Model Sample

Sample Model

Sensitivity: Internal
MVC – View Sample

Sample View

Sample View with Model binding

Sensitivity: Internal
MVC - View

Razor and HTML Helper Syntax

1
Sensitivity: Internal
MVC – Controller Sample

Sample Controller

 The Controller handles incoming URL requests.

 MVC routing sends requests to the appropriate controller and action


method based on URL and configured Routes.

 All the public methods in the Controller class are called Action methods.

 The Controller class must be derived from System.Web.Mvc.Controller


class.

 The Controller class name must end with "Controller“.

Sensitivity: Internal
MVC – Routing

Routing

•Routing

• Routing enables us to define a URL


pattern that maps to the request
handler.
• All the configured routes of an
application stored in RouteTable
• RouteTable is used by Routing
engine to determine appropriate
handler class or file for an
incoming request.

1
Sensitivity: Internal
MVC – Route Config

 Every MVC application must configure


(register) at least one route configured
by the MVC framework by default.

 We can register a route in RouteConfig


class(RouteConfig.cs) located in
App_Start folder.

 We can have more than one route.

1
Sensitivity: Internal
MVC - Routing

Multiple Routing

1
Sensitivity: Internal
MVC – Razor View

 Razor is one of the view engines supported in


ASP.NET MVC.

 Razor allows you to write a mix of HTML and


server-side code using C# or Visual Basic.

 Start with @ symbol to write server-side C# or


VB code with HTML code,
Eg. @Variable_Name to display the value of a
server-side variable.
Eg. @DateTime.Now to display the current
date and time.

1
Sensitivity: Internal
MVC – HTML Helpers

 The HtmlHelper class renders HTML controls in the razor view.

 It binds the model object to HTML controls to display the value of


model properties into those controls.

 Also assigns the value of the controls to the model properties


while submitting a web form.

 HtmlHelper method is designed to make it easy to bind to view


data or model data.

1
Sensitivity: Internal
MVC – HTML Helper

1
Sensitivity: Internal
MVC _ HTML Helpers

1
Sensitivity: Internal
MVC - Validation

Data Annotation :

 ASP.NET MVC includes built-in attribute classes in the System.ComponentModel.DataAnnotations namespace.

 These attributes are used to define metadata for ASP.NET MVC and ASP.NET data controls.

 We can apply these attributes to the properties of the model class to display appropriate validation messages to
the users.

1
Sensitivity: Internal
MSC - Data Annotation

Data Annotation Sample

1
Sensitivity: Internal
MVC – Layout view

 ASP.NET MVC introduced a Layout view which contains these common UI portions so that we don't have to
write the same code in every page.
eg. header, left navigation bar, right bar, or footer section

 For example, An application UI may contain a header, left menu bar, right bar, and footer section that remains the
same on every page. Only the center section changes dynamically, as shown below

 The layout view allows you to define a common site template, which
can be inherited in multiple views to provide a consistent look and
feel in multiple pages of an application.

 The layout view eliminates duplicate coding and enhances


development speed and easy maintenance.

 The layout view for the sample UI would contain a Header, Left
Menu, Right bar, and Footer sections. It has a placeholder for the
center section that changes dynamically.

1
Sensitivity: Internal
MVC - Layout

 The layout view has the same extension as other


views, .cshtml or .vbhtml.

 Layout views are shared with multiple views, so it must be


stored in the Shared folder.

 By default, a layout view _Layout.cshtml is created when you


Create MVC application using Visual Studio, as shown below.

1
Sensitivity: Internal
MVC - Layout

 The layout view contains HTML


Doctype, head, and body tags. The
only difference is a call to
RenderBody() and RenderSection()
methods.

 The child views will be displayed where


the RenderBody() is called.

1
Sensitivity: Internal
MVC - ViewStart

 The default _ViewStart.cshtml is included


in the Views folder.
 It can also be created in all other Views
sub-folders.
 It is used to specify common settings for
all the views under a folder and sub-
folders where it is created.
 Set the Layout property to a particular
layout view will be applicable to all the
child views under that folder and its sub-
folders

1
Sensitivity: Internal
MVC – Layout in Child view/Action method

 We can also override the default


layout view setting of
_ViewStart.cshtml by setting the
Layout property in each child view as
shown

 Specify the layout view name as a second parameter in the View() method, as shown below. By default, layout view
will be searched in the Shared folder.

1
Sensitivity: Internal
MVC – Partial View

 A partial view is a reusable portion of


a web page. It is .cshtml or .vbhtml file
that contains HTML code.

 It can be used in one or more Views or


Layout Views.

 We can use the same partial view at


multiple places and eliminates the
redundant code.

1
Sensitivity: Internal
MVC – Render Partial View

 We can render the partial view in the parent view using the HTML
helper methods:
@html.Partial(), html.RenderPartial(), @html.RenderAction().

Html.Partial() Html.RenderPartial()
 Html.Partial returns html string.  Html.RenderPartial returns void.
 Html.Partial injects the html string of the partial  Html.RenderPartial writes html in the response
view into the main view stream.

1
Sensitivity: Internal
MVC – Render Action

 The @html.RenderAction() method executes the specified


action method and renders the result.

 The specified action method must be marked with the


[ChildActionOnly] attribute and return the PartialViewResult
using the PartialView() method.

1
Sensitivity: Internal
MVC – Action Method

Action Method :
 All the public methods of the Controller class are called Action methods.
 They are like any other normal methods with the following restrictions:
 Action method must be public. It cannot be private or protected
 Action method cannot be overloaded
 Action method cannot be a static method.

Default Action Method :


 Every controller can have a default action method as per the configured
route in the RouteConfig class.
 By default, the Index() method is a default action method for any
controller, as per configured default root.

1
Sensitivity: Internal
MVC – Action Result

Action Result :
 MVC framework includes various Result classes, which can
be returned from an action method.
 The result classes represent different types of responses,
such as HTML, file, string, JSON, javascript, etc

1
Sensitivity: Internal
MSC – Action Verbs

 The ActionVerbs selector is to handle different type of Http requests.

 We can apply one or more action verbs to an action method to handle different HTTP
requests.

 HttpGet is the default ActionVerb.

1
Sensitivity: Internal
MVC – Action Verbs

1
Sensitivity: Internal
MVC – Action Verbs

 Multiple Action verbs

1
Sensitivity: Internal
MVC – View Bag

ViewBag :
 ViewBag is used to transfer temporary data (which is not included in the model) from the controller to the view.
 ViewBag doesn't require typecasting while retrieving values from it. This can throw a run-time exception if the
wrong method is used on the value.
 ViewBag is a dynamic type and skips compile-time checking. So, ViewBag property names must match in
controller and view while writing it manually.

1
Sensitivity: Internal
MVC – View Data

View Data:

 ViewData is similar to ViewBag, which transfers data from Controller to View.


 ViewData is of Dictionary type, whereas ViewBag is of dynamic type. However, both store data in the same dictionary
internally.
 ViewData is a dictionary, so it contains key-value pairs where each key must be a string.
 ViewData only transfers data from controller to view, not vice-versa. It is valid only during the current request.
 ViewData values will be cleared if redirection occurs

1
Sensitivity: Internal
MVC – Temp Data

 TempData is used to transfer data from  TempData stores the data temporarily for one
view to controller, controller to view, or request. If we want to retrieve data for next
from one action method to another action request we can use keep().
method of the same or a different
controller.

1
Sensitivity: Internal
MVC - Filter

 controllers define action methods that usually have a one-to-one relationship with possible user
interactions, but sometimes you want to perform logic either before an action method is called or after
an action method runs

 Filters are custom classes that provide both a declarative and programmatic means to add pre-action
and post-action behavior to controller action methods.

 Declarative - applying a filter attribute to an action method or controller class.

 Programmatic - implementing a corresponding interface

1
Sensitivity: Internal
MVC - Filter

Register Filters :
Filters can be applied at three levels

 Global Level Filters

 Controller Level Filters

 Action Method Filters

1
Sensitivity: Internal
MVC - Filter

Global Level Filters :


 We can apply filters at a global level in the Application_Start event of the global.asax.cs file by using default
FilterConfig.RegisterGlobalFilters() method.
 The global filters will be applied to all the controller and action methods of an application
 The [HandleError] filter is applied globally in the MVC application by default in every MVC application created
using Visual Studio.

Controller Level Filters :


 Controller level filters are
applied to all the action
methods.
 The following filter are
applicable to all the action
methods of the
HomeController, but not
on other controllers.

1
Sensitivity: Internal
MVC - Filter

Action Method Filters :


 One or more filters can also apply to an individual action method. The following filter applied only on the Index()
action method.

1
Sensitivity: Internal
MVC – Bundling & Minification

 Bundling and minification techniques were introduced in MVC 4 to improve request load time.
 Bundling allows us to load the bunch of static files from the server in a single HTTP request.
 Minification technique optimizes script or CSS file size by removing unnecessary white space and comments
and shortening variable names to one character.
Bundling Minification

1
Sensitivity: Internal
MVC – Bundle Types

1
Sensitivity: Internal
MVC - Area

 Area allows us to partition the large application into


smaller units where each unit contains a separate
MVC folder structure

 Each area includes the AreaRegistration class

 All the areas must be registered in the Application_Start event in


Global.asax.cs as AreaRegistration.RegisterAllAreas();

1
Sensitivity: Internal
MVC - Area

1
Sensitivity: Internal
MVC – Global.asax.cs

global.asax allows you to write code that runs in response to


"system level" events, such as the application starting, a session
ending, an application error occuring, without having to try and
shoe-horn that code into each and every page of your site.

1
Sensitivity: Internal
MVC – App_Start

 App_Start is used to contain the class files which


are needed to be executed at the time the Packages.config
application starts
 Packages.config file is managed by NuGet to track what
packages and versions you have installed in the
application.

1
Sensitivity: Internal
MVC – Web.config

 Web.config file contains application-level configurations.

1
Sensitivity: Internal
Sensitivity: Internal

You might also like