MVC Introduction, Overview & Architecture - Part 1 - PowerPoint PPT Presentation

About This Presentation
Title:

MVC Introduction, Overview & Architecture - Part 1

Description:

This PPT is all about the MVC framework where you can get the information on MVC introduction, MVC overview & MVC architecture and that is very useful for the .NET Programmers, developers & beginners. – PowerPoint PPT presentation

Number of Views:2285
Slides: 48
Provided by: ifourtechnolab
Category: Other

less

Transcript and Presenter's Notes

Title: MVC Introduction, Overview & Architecture - Part 1


1
iFour Consultancy
https//www.ifourtechnolab.com/
2
Introduction to MVC
  • Software design pattern for developing web
    applications
  • Software architecture pattern which separates the
    representation of information from the users
    interaction with it
  • Here M stands for Model, V stands for View
    and C stands for controller
  • ASP.NET MVC helps to develop powerful and
    pattern-based dynamic websites that enables a
    clean separation of concerns and also gives full
    control on a mark-up
  • Also it includes many features that help to
    develop a sophisticated and modern web application

https//www.ifourtechnolab.com/
3
MVC vs WEB FORMS
MVC Web Forms
Easier to Manage Complexity Preservers State over HTTP
Does not use view state or server based forms Page Controller Pattern
Rich Routing Structure View state or server based forms
Support for Test-Driven Development Works well for small teams
Supports Large Teams Well Development is less complex
https//www.ifourtechnolab.com/
4
Architecture of MVC
  • A markup language is a set of markup tags
  • A Model View Controller pattern is made up of the
    following three parts
  • Model
  • View
  • Controller

https//www.ifourtechnolab.com/
5
Architecture of MVC (Cont.)
  • A markup language is a set of markup tags
  • Model
  • Responsible for managing the data of the
    application
  • It responds to the request from the view and it
    also responds to instructions from the controller
    to update itself
  • Lowest level pattern which is responsible for
    maintaining data
  • Represents the application core (for instance a
    list of database records)
  • Also called the domain layer

https//www.ifourtechnolab.com/
6
Architecture of MVC (Cont.)
  • A markup language is a set of markup tags
  • View
  • The View displays the data (the database records)
  • A view requests information from the model, that
    it needs to generate an output representation
  • Presents data in a particular format like JSP,
    ASP, PHP
  • MVC is often seen in web applications, where the
    view is the HTML page

https//www.ifourtechnolab.com/
7
Architecture of MVC (Cont.)
  • A markup language is a set of markup tags
  • Controller
  • It is the part of the application that handles
    user interaction
  • Typically controllers read data from a view,
    control user input, and send input data to the
    model
  • It handles the input, typically user actions and
    may invoke changes on the model and view

https//www.ifourtechnolab.com/
8
Routing
  • A markup language is a set of markup tags
  • A route is a URL pattern that is mapped to a
    handler
  • The handler can be a physical file, such as an
    .aspx file in a Web Forms application. A handler
    can also be a class that processes the request,
    such as a controller in an MVC application
  • At runtime, Routing engine use the Route table
    for matching the incoming request's URL pattern
    against the URL patterns defined in the Route
    table
  • Register one or more URL patterns to the Route
    table at Application_Start event
  • When the routing engine finds a match in the
    route table for the incoming request's URL, it
    forwards the request to the appropriate
    controller and action
  • If there is no match in the route table for the
    incoming request's URL, it returns a 404 HTTP
    status code

https//www.ifourtechnolab.com/
9
How it works?
  • A markup language is a set of markup tags

https//www.ifourtechnolab.com/
10
How to define route?
  • A markup language is a set of markup tags
  • public static void RegisterRoutes(RouteCollection
    routes)
  • routes.MapRoute(
  • "Default", //Route
    name
  • "controller/action/id",
    //URL with
    parameters
  • new controller "Home", action
    "Index", id UrlParameter.Optional //Default
    parameters
  • )
  • protected void Application_Start()
  • RegisterRoutes(RouteTable.Routes)
  • //ToDO

https//www.ifourtechnolab.com/
11
Bundling
  • A markup language is a set of markup tags
  • It is a simple logical group of files that could
    be referenced by unique name and being loaded
    with one HTTP requestor
  • Bundling and minification reduces the number of
    HTTP Requests and payload size resulting in
    faster and better performing ASP.NET MVC Websites

https//www.ifourtechnolab.com/
12
How to define bundling?
  • A markup language is a set of markup tags
  • public static void RegisterBundles(BundleCollectio
    n bundles)
  • bundles.Add(new ScriptBundle("/bundles/jque
    ryval").Include(
  • "/Scripts/jquery.unobtrusi
    ve",
  • /Scripts/my_custom_js.js
    ,
  • .....List of
    Js..............))
  • protected void Application_Start()
  • BundleConfig.RegisterBundles(BundleTable.Bundles)

https//www.ifourtechnolab.com/
13
Filter
  • A markup language is a set of markup tags
  • ASP.NET MVC Filter is a custom class where you
    can write custom logic to execute before or after
    an action method executes
  • Filters can be applied to an action method or
    controller in a declarative or programmatic way
  • MVC provides different types of filters

Filter Type Description Built-in Filter Interface
Authorization filters Performs authentication and authorizes before executing action method Authorize RequireHttps IAuthorizationFilter
Action filters Performs some operation before and after an action method executes IActionFilter
Result filters Performs some operation before or after the execution of view result OutputCache IResultFilter
Exception filters Performs some operation if there is an unhandled exception thrown during the execution of the ASP.NET MVC pipeline HandleError IExceptionFilter
https//www.ifourtechnolab.com/
14
Filter
  • A markup language is a set of markup tags
  • Filters can be applied at three levels
  • Global Level Global filters will be applied to
    all the controller and action methods of an
    application
  • // MvcApplication class contains in
    Global.asax.cs file
  • public class MvcApplication System.Web.HttpAppli
    cation
  • protected void Application_Start()
  • FilterConfig.RegisterGlobalFilters(Gl
    obalFilters.Filters)
  • // FilterConfig.cs located in App_Start folder
  • public class FilterConfig
  • public static void RegisterGlobalFilters(Glob
    alFilterCollection filters)
  • filters.Add(new HandleErrorAttribute(
    ))

https//www.ifourtechnolab.com/
15
Filter
  • A markup language is a set of markup tags
  • Controller Level Filters can also be applied to
    the controller class. So, filters will be
    applicable to all the action method of Controller
    class if it is applied to a controller class
  • HandleError
  • public class HomeController Controller
  • public ActionResult Index()
  • return View()

https//www.ifourtechnolab.com/
16
Filter
  • A markup language is a set of markup tags
  • Action method level Apply filters to an
    individual action method. So, filter will be
    applicable to that particular action method only.
  • public class HomeController Controller
  • HandleError
  • public ActionResult Index()
  • return View()
  • Filters run in the following order.
  • Authorization filters, Action filters, Response
    filters, Exception filters

https//www.ifourtechnolab.com/
17
Custom Filter
  • A markup language is a set of markup tags
  • Create custom filter attributes by implementing
    an appropriate filter interface for which creates
    custom filter and also derive a FilterAttribute
    class
  • For example
  • Implement IExceptionFilter and FilterAttribute
    class to create custom exception filter. In the
    same way implement an IAuthorizatinFilter
    interface and FilterAttribute class to create a
    custom authorization filter

https//www.ifourtechnolab.com/
18
Custom Filter Example
  • A markup language is a set of markup tags
  • class MyErrorHandler FilterAttribute,
    IExceptionFilter
  • public override void IExceptionFilter.OnExcept
    ion(ExceptionContext filterContext)
  • Log(filterContext.Exception)
  • base.OnException(filterContext)
  • private void Log(Exception exception)
  • //log exception here..

https//www.ifourtechnolab.com/
19
Actions
  • Actions are the ultimate request destination
  • Public controller methods
  • Non-static
  • No return value restrictions
  • Actions typically return an ActionResult

https//www.ifourtechnolab.com/
20
Action Result
  • Controller action response to a browser request
  • Inherits from the base ActionResult class
  • Different results types

https//www.ifourtechnolab.com/
21
Action Result (Cont.)
https//www.ifourtechnolab.com/
22
Action Parameters
  • ASP.NET MVC maps the data from the HTTP request
    to action parameters in few ways
  • Routing engine can pass parameters to actions
  • http//localhost/Users/IFour
  • Routing pattern Users/username
  • URL query string can contains parameters
  • /Users/ByUsername?usernameIFour
  • HTTP post data can also contain parameters

https//www.ifourtechnolab.com/
23
Action Selection
  • ActionName(string name)
  • AcceptVerbs
  • HttpPost
  • HttpGet
  • HttpDelete
  • HttpOptions
  • NonAction
  • RequireHttps
  • ChildActionOnly Only for Html.Action()

https//www.ifourtechnolab.com/
24
Action Filters
  • A markup language is a set of markup tags
  • ASP.NET MVC provides the following types of
    action filters
  • Authorization filter, which makes security
    decisions about whether to execute an action
    method, such as performing authentication or
    validating properties of the request
  • The AuthorizeAttribute class is one example of an
    authorization filter
  • Action filter, which wraps the action method
    execution
  • Perform additional processing, such as providing
    extra data to the action method, inspecting the
    return value, or canceling execution of the
    action method
  • Result filter, which wraps execution of the
    ActionResult object. This filter can perform
    additional processing of the result, such as
    modifying the HTTP response
  • The OutputCacheAttribute class is one example of
    a result filter
  • Exception filter, which executes if there is an
    unhandled exception thrown somewhere in action
    method, starting with the authorization filters
    and ending with the execution of the result

https//www.ifourtechnolab.com/
25
How To Apply an Action Filter?
  • A markup language is a set of markup tags
  • An attribute that implements the abstract
    FilterAttribute class
  • Some action filters, such as AuthorizeAttribute
    and HandleErrorAttribute, implement the
    FilterAttribute class directly, these action
    filters are always called before the action
    method runs
  • Other action filters, such as OutputCacheAttribute
    , implement the abstract ActionFilterAttribute
    class, which enables the action filter to run
    either before or after the action method runs
  • Use the action filter attribute to mark any
    action method or controller. If the attribute
    marks a controller, the action filter applies to
    all action methods in that controller
  • The following example shows the default
    implementation of the HomeController class
  • In the example, the HandleError attribute is used
    to mark the controller. Therefore, the filter
    applies to both action methods in the controller

https//www.ifourtechnolab.com/
26
Example for Action Filter
  • A markup language is a set of markup tags
  • HandleError
  • public class HomeController Controller
  • public ActionResult Index()
  • ViewData"Message" "Welcome to
    ASP.NET MVC!"
  • return View()
  • OutputCache(Duration10)
  • public ActionResult About()
  • return View()

https//www.ifourtechnolab.com/
27
Razor
  • Template markup syntax
  • Simple-syntax view engine
  • Based on the C programming language
  • Enables the programmer to use an HTML
    construction workflow
  • Code-focused templating approach, with minimal
    transition between HTML and code
  • Razor syntax starts code blocks with a _at_
    character and does not require explicit closing
    of the code-block

https//www.ifourtechnolab.com/
28
Razor Syntax
  • _at_ - For values (HTML encoded)
  • _at_ - For code blocks (keep the view simple!)

ltpgt Current time is _at_DateTime.Now!!!
Not HTML encoded value _at_Html.Raw(someVar) lt/pgt
_at_ var productName "Energy drink" if
(Model ! null) productName
Model.ProductName else if
(ViewBag.ProductName ! null)
productName ViewBag.ProductName
ltpgtProduct "_at_productName" has been added in
shopping cartlt/pgt
https//www.ifourtechnolab.com/
29
Razor Syntax (Cont.)
  • If, else, for, foreach, etc. C statements
  • HTML markup lines can be included at any part
  • _at_ For plain text line to be rendered

ltdiv class"products-list"gt _at_if
(Model.Products.Count() 0) ltpgtSorry, no
products found!lt/pgt else _at_List of the
products found foreach(var product in
Model.Products) ltbgt_at_product.Name,lt/b
gt lt/divgt
https//www.ifourtechnolab.com/
30
Layout
  • Define a common site template
  • Similar to ASP.NET master pages (but better!)
  • Razor view engine renders content inside-out
  • First view is rendered, then layout
  • _at_RenderBody() - Indicate where we want the views
    based on thislayout to fill in their core
    content at thatlocation in the HTML

https//www.ifourtechnolab.com/
31
View and Layout
  • Views don't need to specify layout since their
    default layout is set in their _ViewStart file
  • /Views/_ViewStart.cshtml (code for all views)
  • Each view can specify custom layout pages
  • Views without layout

_at_ Layout "/Views/Shared/_UncommonLayout.c
shtml"
_at_ Layout null
https//www.ifourtechnolab.com/
32
HTML Helpers in MVC
  • With MVC, HTML helpers are much like traditional
    ASP.NET Web Form controls
  • Just like web form controls in ASP.NET, HTML
    helpers are used to modify HTML. But HTML helpers
    are more lightweight. Unlike Web Form controls,
    an HTML helper does not have an event model and a
    view state
  • In most cases, an HTML helper is just a method
    that returns a string
  • With MVC, you can create your own helpers, or use
    the built in HTML helpers

https//www.ifourtechnolab.com/
33
HTML Helpers in MVC (Cont.)
https//www.ifourtechnolab.com/
34
HTML Helpers in MVC (Cont.)
https//www.ifourtechnolab.com/
35
Partial View
  • Partial views render portions of a page
  • Reuse pieces of a view
  • Html helpers Partial, RenderPartial and Action
  • Razor partial views are still .cshtml files

Located in the same folder as other views or in
Shared folder
https//www.ifourtechnolab.com/
36
Areas
  • Some applications can have a large number of
    controllers
  • ASP.NET MVC lets us partition Web applications
    into smaller units (areas)
  • An area is effectively an MVC structure inside an
    application
  • Example large e-commerce application
  • Main store, users
  • Blog, forum
  • Administration

https//www.ifourtechnolab.com/
37
MVC STATE MANAGEMENT
  • It is the process by which developers can
    maintain state and page information over multiple
    request for the same or different pages in web
    application
  • Methods which are used in ASP.NET MVC
    applications
  • Hidden Field
  • Cookies
  • Query strings
  • ViewData
  • ViewBag
  • TempData

https//www.ifourtechnolab.com/
38
MVC STATE MANAGEMENT (Cont.)
  • HiddenField
  • Used to store small amounts of data on the client
    system. It is a preferable way when a variables
    value is changed frequently. The only constraint
    on hidden filed is that it will keep the
    information when HTTP post is being done. It will
    not work with HTTP get
  • For example to store in hidden field in MVC view
    page like

https//www.ifourtechnolab.com/
39
MVC STATE MANAGEMENT (Cont.)
  • Cookies
  • Small text file which is created by the server
    and stored on the client hard disk by the
    browser. It does not use server memory. Generally
    a cookie is used to identify users
  • When user sends a request to the server, the
    server creates a cookie and attaches a header and
    sends it back to the user along with the response
  • The browser accepts the cookie and stores it on
    the client machine either permanently or
    temporarily. The next time the user makes a
    request for the same site, the browser checks the
    existence of the cookie for that site in the
    folder
  • Cookies are two types
  • Persistence  Cookies are permanently stored till
    the time we set
  • Non-Persistence  Cookies are not permanently
    stored on the users system. When user closes the
    browser the cookie will be discarded

https//www.ifourtechnolab.com/
40
MVC STATE MANAGEMENT (Cont.)
  • Example
  • Note 
  • The number of cookies allowed is varies
    according to the browser. Most browsers allow 20
    cookies per server in a client's hard disk folder
    and the size of a cookie is not more than 4 KB of
    data

https//www.ifourtechnolab.com/
41
MVC STATE MANAGEMENT (Cont.)
  • Query Strings
  • String variable which is appended to the end of
    the Page URL
  • Used to send data across pages
  • Stores information in a key/value pair. A ?
    signature is used to append the key and value to
    the page URL
  • In MVC application, pass query string values
    along with a route parameter id like
    http//MyDomain/product/Edit/1?nameMobile
  • Note Most browsers impose a limit of 255
    characters on URL length. We should encrypt query
    values.

https//www.ifourtechnolab.com/
42
MVC STATE MANAGEMENT (Cont.)
  • ViewData
  • Dictionary object which is derived
    from ViewDataDictionary class. It will be
    accessible using strings as keys
  • It lies only during the current request from
    controller to respective view . If redirection
    occurs then its value becomes null. It required
    typecasting for getting data on view

https//www.ifourtechnolab.com/
43
MVC STATE MANAGEMENT (Cont.)
  • ViewBag
  • Dynamic property which is wrapped around the
    ViewData object. Dynamic property is a new
    feature in ASP.NET Dynamic Language.
  • We can simply set properties on the dynamic
    ViewBag property within controller
  • It also lies only during the current request from
    controller to respective view as ViewData, If
    redirection occurs its value becomes null. It
    does not required typecasting for getting data on
    view
  • Note Both viewdata and viewbag are almost
    similar and helps to maintain data, they provide
    a way to communicate between controllers and
    views

https//www.ifourtechnolab.com/
44
MVC STATE MANAGEMENT (Cont.)
  • Similarities between ViewBag ViewData
  • Helps to maintain data during movement from
    controller to view
  • Used to pass data from controller to
    corresponding view
  • Short life means value becomes null when
    redirection occurs. This is because their goal is
    to provide a way to communicate between
    controllers and views. Its a communication
    mechanism within the server call
  • Difference between ViewBag ViewData
  • ViewData is a dictionary of objects that is
    derived from ViewDataDictionary class and
    accessible using strings as keys
  • ViewBag is a dynamic property that takes
    advantage of the new dynamic features in C 4.0
  • ViewData requires typecasting for complex data
    type and check for null values to avoid error
  • ViewBag doesnt require typecasting for complex
    data type

https//www.ifourtechnolab.com/
45
MVC STATE MANAGEMENT (Cont.)
  • TempData
  • Dictionary object which stores data as key/value
    pair and derived from TempData Dictionary class.
  • TempData helps to maintain data when we move from
    one controller to other controller or from one
    action to other action. In other words it helps
    to maintain data between redirects
  • RedirectToAction has no impact over the TempData
    until TempData is read. Once TempData is read its
    values will be lost

https//www.ifourtechnolab.com/
46
MVC STATE MANAGEMENT (Cont.)
  • TempData (Cont.)
  • Note TempData.Keep() method is used to keep data
    in controllers as long as we wish

https//www.ifourtechnolab.com/
47
References
  • https//www.tutorialspoint.com/mvc_framework/mvc_
    framework_introduction.htm
  • http//www.tutorialspoint.com/asp.net_mvc/
  • https//msdn.microsoft.com/en-us/library/dd381412
    (vvs.108).aspx
  • http//www.tutorialsteacher.com/mvc/asp.net-mvc-t
    utorials

https//www.ifourtechnolab.com/
Write a Comment
User Comments (0)
About PowerShow.com