+ All Categories
Home > Documents > 1 P a g eAjax Helpers Auto binding MVC 2.0 VS 2008, .Net 3.5/4.0 10 -Mar -2010 Area Asynchronous...

1 P a g eAjax Helpers Auto binding MVC 2.0 VS 2008, .Net 3.5/4.0 10 -Mar -2010 Area Asynchronous...

Date post: 31-Jan-2021
Category:
Upload: others
View: 2 times
Download: 0 times
Share this document with a friend
117
1 | Page KnackHook Knowledge Holder [email protected] www.knackhook.com MVC
Transcript
  • 1 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    MVC

    mailto:[email protected]://www.knackhook.com/

  • 2 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    Table of Contents 1. What is MVC? ...................................................................................................... 5

    2. MVC Components ................................................................................................ 5

    3. ASP.NET MVC Features: ....................................................................................... 6

    4. Disadvantages of ASP.Net: .................................................................................. 6

    5. Reasons to move from asp.net to mvc: ................................................................ 6

    6. Advantages of MVC: ............................................................................................ 7

    7. ASP.NET MVC History: ......................................................................................... 7

    Asp.Net MVC 1.0 .............................................................................................................................. 7

    Asp.Net MVC 2.0 .............................................................................................................................. 7

    Asp.Net MVC 3.0 .............................................................................................................................. 8

    Asp.Net MVC 4.0 .............................................................................................................................. 9

    Asp.Net MVC 5.0 .............................................................................................................................. 9

    8. Deciding When to Create a Web Forms Application ........................................... 11

    9. Advantages of a Web Forms-Based Web Application: ....................................................................................................... 11

    10. Advantages of an MVC-Based Web Application: ................................................ 11

    11. MVC Application Execution Process: .................................................................. 11

    12. MVC Models: ..................................................................................................... 12

    The Models Folder: ........................................................................................................................ 13

    Adding a Database Model: ............................................................................................................. 13

    Adding a Database Controller: ....................................................................................................... 14

    Adding Database Views: ................................................................................................................ 14

    Adding a Connection String: .......................................................................................................... 14

    13. Controller: ......................................................................................................... 14

    Adding New Controller: ................................................................................................................. 15

    Add New Controller: ...................................................................................................................... 15

    mailto:[email protected]://www.knackhook.com/

  • 3 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    14. Action Methods: ................................................................................................ 18

    Default Action method: ................................................................................................................. 19

    ActionResult: .................................................................................................................................. 20

    Action method Parameters: ........................................................................................................... 21

    Action Result Type: ........................................................................................................................ 21

    Action Results Listing: .................................................................................................................... 21

    15. Action Selectors................................................................................................. 23

    ActionName Selector ..................................................................................................................... 24

    NonAction: ..................................................................................................................................... 24

    ActionVerbs: ................................................................................................................................... 25

    16. Action Filters ..................................................................................................... 27

    Authorize ........................................................................................................................................ 28

    ChildActiononly .............................................................................................................................. 28

    HandleError .................................................................................................................................... 29

    OutputCache .................................................................................................................................. 30

    CacheProfiles in MVC ..................................................................................................................... 31

    RequireHttps .................................................................................................................................. 33

    Validatelnput.................................................................................................................................. 33

    ValidateAntiForgeryToken ............................................................................................................. 34

    Types of filters in MVC ................................................................................................................... 34

    17. Views ................................................................................................................ 35

    Adding Content to a View .............................................................................................................. 36

    Using HTML Helpers to Generate View Content ........................................................................... 37

    Using View Data to Pass Data to a View ........................................................................................ 40

    18. View engines ..................................................................................................... 41

    Aspx View Engine ........................................................................................................................... 41

    Razor View Engine.......................................................................................................................... 42

    19. Data Transfer in MVC ........................................................................................ 47

    Model ............................................................................................................................................. 47

    ViewModel ..................................................................................................................................... 50

    ViewData and ViewBag .................................................................................................................. 53

    mailto:[email protected]://www.knackhook.com/

  • 4 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    TempData ....................................................................................................................................... 55

    Sessions .......................................................................................................................................... 56

    20. Strongly typed Views ......................................................................................... 57

    21. Post data to a controller .................................................................................... 60

    Pass data from View to Controller in ASP.Net MVC ...................................................................... 60

    22. HTML Helpers .................................................................................................... 63

    Inline Html Helpers ........................................................................................................................ 63

    Built-In Html Helpers...................................................................................................................... 64

    Custom Html Helpers ..................................................................................................................... 67

    23. Validations in MVC ............................................................................................ 68

    Using the Code ............................................................................................................................... 68

    By using Data Annotations ............................................................................................................. 69

    By using ModelState object (Explicit Model Validation)................................................................ 70

    By Using Fluent Validation Package ............................................................................................... 75

    24. Layout Page ....................................................................................................... 77

    Using Layout View .......................................................................................................................... 81

    Rendering Methods: ...................................................................................................................... 85

    Create Layout View ........................................................................................................................ 87

    25. Partial Views ..................................................................................................... 91

    Create New Partial View ................................................................................................................ 92

    Rendering Partial View ................................................................................................................... 94

    26. Bundling ............................................................................................................ 98

    ScriptBundle in ASP.NET MVC ........................................................................................................ 99

    StyleBundle in ASP.NET MVC ....................................................................................................... 103

    27. Minification ..................................................................................................... 105

    28. Areas ............................................................................................................... 105

    Create Area .................................................................................................................................. 106

    29. MVC 6.0 .......................................................................................................... 109

    MVC 6 ........................................................................................................................................... 110

    New features in MVC 6 ................................................................................................................ 111

    mailto:[email protected]://www.knackhook.com/

  • 5 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    Important components of an MVC 6 Application ........................................................................ 112

    What is MVC?

    The Model-View-Controller (MVC) is an architectural pattern that separates an application into three main logical components: the model, the view, and the controller. Each of these components are built to handle specific development aspects of an application. MVC is one of the most frequently used industry-standard web development framework to create scalable and extensible projects.

    MVC Components

    Model: The Model component corresponds to all the data related logic that the user works with. This can represent either the data that is being transferred between the View and Controller components or any other business logic related data. For example, a Customer object will retrieve the customer information from the database, manipulate it and update it data back to the database or use it to render data.

    View: The View component is used for all the UI logic of the application. For example, the Customer view would include all the UI components such as text boxes, dropdowns, etc. that the final user interacts with.

    Controller: Controllers act as an interface between Model and View components to process all the business logic and incoming requests, manipulate data using the Model component and interact with the Views to render the final output. For example, the Customer controller would handle all the interactions and inputs from the Customer View and update the database using the Customer Model. The same controller would be used to view the Customer data.

    mailto:[email protected]://www.knackhook.com/

  • 6 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    ASP.NET MVC Features:

    The ASP.NET MVC provides the following features:

    Ideal for developing complex but light weight applications

    It provides an extensible and pluggable framework which can be easily replaced and customized. For example, if you do not wish to use the in-built Razor or ASPX View Engine, then you can use any other third-party view engines or even customize the existing ones.

    Utilizes the component-based design of the application by logically dividing it into Model, View and Controller components. This enables the developers to manage the complexity of large-scale projects and work on individual components.

    The MVC structure enhances the test-driven development and testability of the application since all the components can be designed interface-based and tested using mock objects. Hence the ASP.NET MVC Framework is ideal for projects with large team of web developers.

    Supports all the existing vast ASP.NET functionalities such as Authorization and Authentication, Master Pages, Data Binding, User Controls, Memberships, ASP.NET Routing, etc.

    It does not use the concept of View State (which is present in ASP.NET). This helps in building applications which are light-weight and gives full control to the developers.

    Thus, you can consider MVC Framework as a major framework built on top of ASP.NET providing a large set of added functionality with focus on component-based development and testing.

    Disadvantages of ASP.Net:

    In asp.net all the controls are server side controls and also which are heavy weight controls. As asp.net controls ae server side controls they will take more time to load the webform.

    There is a tightly coupled behavior in between aspx and aspx.cs pages.

    Aspx pages are not much suitable for the search engine optimization (SEO).

    Automation Testing is not completely suitable for the asp.net applications.

    Reasons to move from asp.net to mvc:

    1. TDD support out of the box as most of the design is based on interfaces. 2. SEO friendly URL by design (though now this is possible in ASP.NET 4 as well) 3. No ViewState (this may seem a bit of moving backward to some), but overall a good design decision. 4. Clean View Markup (no additional HTML emitted) 5. 100% extensible. You can add your own controller with IOC, switch view engines at will, control model binding at wish etc. 6. Rich UI support (possible through client side JS libraries like jQuery UI and others). Telerik has released some controls for MVC which includes Grid control as well (which are merely HTMLHelpers) 7. Session, JS, Ajax works. Validation is even more powerful with DataAnnotations and jquery. 8. Is MVC faster? Yes, by default because of lack of viewstate and clean markup. But performance is subject and MVC by design is more performant that traditional ASP.NET webforms (though webforms can be made as fast as required.

    mailto:[email protected]://www.knackhook.com/

  • 7 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    9. Out of the box support for mitigating antiforgery attacks and XSS vulnerability (though asp.net does has this to some extent) 10. Out of the box minimal IOC support. 11. Full control over rendered HTML 12. Pluggable architecture etc.,

    Advantages of MVC:

    Complete code separation is available in MVC architecture which means, view is not dependent on controller and controller is not dependent on model and model is not dependent on view.

    All controls in view are html controls and light weight controls. It will give better performance compared to asp.net wed forms.

    As all the methods in the controller are normal methods which can be easily tested.

    MVC application does not provide any page extensions on browser url.

    MVC applications are search engine friendly (SEO) application.

    NO event handlers in MVC as in asp.net.

    ASP.NET MVC History:

    Asp.Net MVC is a new Framework built on the top of Microsoft .Net Framework to develop web application. This framework implements the MVC pattern which helps to provides separation of code and also provide better support for test-driven development (TDD).

    Asp.Net MVC is a lightweight and highly testable open source framework for building highly scalable and well-designed web applications. Here is the list of released version history of ASP.NET MVC Framework with theirs features.

    Asp.Net MVC 1.0

    Released on Mar 13, 2009

    Runs on .Net 3.5 and with Visual Studio 2008 & Visual Studio 2008 SP1

    MVC Pattern architecture with WebForm Engine

    Html Helpers

    Ajax helpers

    Routing

    Unit Testing

    Asp.Net MVC 2.0

    mailto:[email protected]://www.knackhook.com/

  • 8 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    Released on Mar 10, 2010

    Runs on .Net 3.5, 4.0 and with Visual Studio 2008 & 2010

    Strongly typed HTML helpers means lambda expression based Html Helpers

    Templated Helpers

    Support for Data Annotations Attribute

    Client-side validation

    UI helpers with automatic scaffolding & customizable templates

    Attribute-based model validation on both client and server

    Overriding the HTTP Method Verb including GET, PUT, POST, and DELETE

    Areas for partitioning a large application into modules

    Asynchronous controllers

    Asp.Net MVC 3.0

    Released on Jan 13, 2011

    Runs on .Net 4.0 and with Visual Studio 2010

    The Razor view engine

    Improved Support for Data Annotations

    Remote Validation

    Compare Attribute

    Sessionless Controller

    Child Action Output Caching

    Dependency Resolver

    Entity Framework Code First support

    Partial-page output caching

    ViewBag dynamic property for passing data from controller to view

    Global Action Filters

    mailto:[email protected]://www.knackhook.com/

  • 9 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    Better JavaScript support with unobtrusive JavaScript, jQuery Validation, and JSON binding

    Use of NuGet to deliver software and manage dependencies throughout the platform

    Good Intellisense support for Razor into Visual Studio

    Asp.Net MVC 4.0

    Released on Aug 15, 2012

    Runs on .Net 4.0, 4.5 and with Visual Studio 2010SP1 & Visual Studio 2012

    ASP.NET Web API

    Enhancements to default project templates

    Mobile project template using jQuery Mobile

    Display Modes

    Task support for Asynchronous Controllers

    Bundling and minification

    Support for the Windows Azure SDK

    Asp.Net MVC 5.0

    Released on 17 October 2013

    Runs on .Net 4.5, 4.5.1 and with Visual Studio 2013

    One Asp.Net

    Asp.Net Identity

    ASP.NET Scaffolding

    Authentication filters - run prior to authorization filters in the ASP.NET MVC pipeline

    Bootstrap in the MVC template

    ASP.NET Web API2

    mailto:[email protected]://www.knackhook.com/

  • 10 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    MVC Version Visual Studio .Net Version Release date Features

    MVC 1.0 VS2008 .Net 3.5 13-Mar-2009 MVC architecture with webform engine

    Routing HTML Helpers Ajax Helpers Auto binding

    MVC 2.0 VS 2008, .Net 3.5/4.0 10-Mar-2010 Area Asynchronous controller Html helper methods with

    lambda expression DataAnnotations

    attributes Client side validation Custom template Scaffolding

    MVC 3.0 VS 2010 .Net 4.0 13-Jan-2011 Unobtrusive javascript validation

    Razor view engine Global filters Remote validation Dependency resolver for

    IoC ViewBag

    MVC 4.0 VS 2010 SP1, VS 2012

    .NET 4.0/4.5 15-Aug-2012 Mobile project template Bundling and minification Support for Windows

    Azure SDK

    MVC 5.0 VS 2013 .NET 4.5 17-oct-2013 Authentication filters Bootstrap support New scaffolding items ASP.Net Identity

    MVC 5.2 - Current

    VS 2013 .NET 4.5 28-Aug-2014 Attribute based routing bug fixes and minor

    features update

    mailto:[email protected]://www.knackhook.com/

  • 11 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    Deciding When to Create a Web Forms Application

    You must consider carefully whether to implement a Web application by using either the ASP.NET Web Forms model or another model, such as the ASP.NET MVC framework. The MVC framework does not replace the Web Forms model; you can use either framework for Web applications. Before you decide to use the Web Forms model or the MVC framework for a specific Web site, weigh the advantages of each approach.

    Advantages of a Web Forms-Based Web Application:

    The Web Forms-based framework offers the following advantages:

    It supports an event model that preserves state over HTTP, which benefits line-of-business Web application development. The Web Forms-based application provides dozens of events that are supported in hundreds of server controls.

    It uses a Page Controller pattern that adds functionality to individual pages. For more information, see Page Controller on the MSDN Web site.

    It uses view state or server-based forms, which can make managing state information easier.

    It works well for small teams of Web developers and designers who want to take advantage of the large number of components available for rapid application development.

    In general, it is less complex for application development, because the components (the Page class, controls, and so on) are tightly integrated and usually require less code than the MVC model.

    Advantages of an MVC-Based Web Application:

    The ASP.NET MVC framework offers the following advantages:

    It makes it easier to manage complexity by dividing an application into the model, the view, and the controller.

    It does not use view state or server-based forms. This makes the MVC framework ideal for developers who want full control over the behavior of an application.

    It uses a Front Controller pattern that processes Web application requests through a single controller. This enables you to design an application that supports a rich routing infrastructure.

    It provides better support for test-driven development (TDD).

    It works well for Web applications that are supported by large teams of developers and Web designers who need a high degree of control over the application behavior.

    MVC Application Execution Process:

    mailto:[email protected]://www.knackhook.com/

  • 12 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    Any web application has two main execution steps first understanding the request and depending on the type of the request sending out appropriate response. MVC application life cycle is not different it has two main phases first creating the request object and second sending our response to the browser.

    Creating Response object: - The request object creation has four major steps. Below is the detail explanation of the same.

    Step 1 Fill route: - MVC requests are mapped to route tables which in turn specify which controller and action to be invoked. So if the request is the first request the first thing is to fill the route table with routes collection. This filling of route table happens in the global.asax file.

    Step 2 Fetch route: - Depending on the URL sent "UrlRoutingModule" searches the route table to create "RouteData" object which has the details of which controller and action to invoke.

    Step 3 Request context created: - The "RouteData" object is used to create the "RequestContext" object.

    Step 4 Controller instance created: - This request object is sent to "MvcHandler" instance to create the controller class instance. Once the controller class object is created it calls the "Execute" method of the controller class.

    Creating Response object: - This phase has two steps executing the action and finally sending the response as a result to the view.

    Step 5 Execute Action: - The "ControllerActionInvoker" determines which action to executed and executes the action.

    Step 6 Result sent: - The action method executes and creates the type of result which can be a view result, file result, JSON result etc.

    So in all there are six broad steps which get executed in MVC application life cycle.

    MVC Models:

    mailto:[email protected]://www.knackhook.com/

  • 13 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    The MVC Model contains all application logic (business logic, validation logic, and data access logic), except pure view and controller logic.

    With MVC, models both hold and manipulate application data.

    The Models Folder:

    The Models Folder contains the classes that represent the application model.

    Visual Web Developer automatically creates an AccountModels.cs file that contains the models for application security.

    AccountModels contains a LogOnModel, a ChangePasswordModel, and a RegisterModel.

    Adding a Database Model:

    The database model needed for this tutorial can be created with these simple steps:

    In the Solution Explorer, right-click the Models folder, and select Add and Class. Name the class MovieDB.cs, and click Add. Edit the class:

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; namespace MvcDemo.Models { public class MovieDB { public int ID { get; set; } public string Title { get; set; } public string Director { get; set; } public DateTime Date { get; set; } } public class MovieDBContext : DbContext { public DbSet Movies { get; set; } } }

    Note:

    mailto:[email protected]://www.knackhook.com/

  • 14 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    We have deliberately named the model class "MovieDB". In the previous chapter, you saw the name "MovieDBs" (ending with s) used for the database table. It looks strange, but this is the naming convention you have to use to make the model connect to the database table.

    Adding a Database Controller:

    The database controller needed for this tutorial can be created with these simple steps:

    Re-Build your project: Select Debug, and then Build MvcDemo from the menu. In the Solution Explorer, right-click the Controllers folder, and select Add and Controller Set controller name to MoviesController Select template: Controller with read/write actions and views, using Entity Framework Select model class: MovieDB (MvcDemo.Models) Select data context class: MovieDBContext (MvcDemo.Models) Select views Razor (CSHTML) Click Add

    Visual Web Developer will create the following files:

    A MoviesController.cs file in the Controllers folder A Movies folder in the Views folder

    Adding Database Views:

    The following files are automatically created in the Movies folder:

    Create.cshtml Delete.cshtml Details.cshtml Edit.cshtml Index.cshtml

    Adding a Connection String:

    Add the following element to the element in your Web.config file:

    Controller:

    The Controller in MVC architecture handles any incoming URL request. Controller is a class, derived from the base class System.Web.Mvc.Controller. Controller class contains public methods

    mailto:[email protected]://www.knackhook.com/

  • 15 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    called Actionmethods. Controller and its action method handles incoming browser requests, retrieves necessary model data and returns appropriate responses.

    In ASP.NET MVC, every controller class name must end with a word "Controller". For example, controller for home page must be HomeController and controller for student must be StudentController. Also, every controller class must be located in Controller folder of MVC folder structure.

    MVC will throw "The resource cannot be found" error when you do not append "Controller" to the controller class name.

    Adding New Controller:

    Now, let's add a new empty controller using Visual Studio 2013 for Web and MVC 5.

    In the previous section we learned how to create our first MVC application, which in turn created a default HomeController. Here, we will create a new StudentController.

    In the Visual Studio, right click on the Controller folder -> select Add -> click on Controller.

    Add New Controller:

    mailto:[email protected]://www.knackhook.com/http://www.tutorialsteacher.com/Content/images/mvc/mvc-controller-1.png

  • 16 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    This opens Add Scaffold dialog as shown below. (Visual Studio 2013 introduced the Add New Scaffold Item dialog. This dialog replaced the Add View/Add Controllers dialog seen in the earlier version of Visual Studio.)

    Note: Scaffolding is an automatic code generation framework for ASP.NET web applications. Scaffolding reduces the time taken to develop a controller, view etc. in MVC framework. You can develop a customized scaffolding template using T4 templates as per your architecture and coding standard.

    Controller Add Scaffold dialog contains different templates to create a new controller. We will learn about other templates later. For now, select "MVC 5 Controller - Empty" and click Add. It will open Add Controller dialog as shown below

    mailto:[email protected]://www.knackhook.com/http://www.tutorialsteacher.com/Content/images/mvc/mvc-controller-2.png

  • 17 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    Controller

    In the Add Controller dialog, enter the name of the controller. Remember, controller name must end with Controller. Let's enter StudentController and click Add.

    Controller

    This will create StudentController class with Index method in StudentController.cs file under Controllers folder, as shown below.

    StudentController in C#:

    using System; using System.Collections.Generic; using System.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVC_BasicTutorials.Controllers { public class StudentController : Controller { // GET: Student public ActionResult Index() { return View(); } } }

    As you can see above, the StudentController class is derived from Controller class. Every controller in MVC must derived from this abstract Controller class. This base Controller class contains helper methods that can be used for various purposes.

    mailto:[email protected]://www.knackhook.com/http://www.tutorialsteacher.com/Content/images/mvc/mvc-controller-3.pnghttp://www.tutorialsteacher.com/Content/images/mvc/mvc-controller-4.png

  • 18 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    Now, we will return a dummy string from Index action method of above StudentController. Changing the return type of Index method from ActionResult to string and returning dummy string is shown below. You will learn about ActionResult in the next section.

    StudentController in C#:

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVC_BasicTutorials.Controllers { public class StudentController : Controller { // GET: Student public string Index() { return "This is Index action method of StudentController"; } } }

    We have already seen in the routing section that the URL request http://localhost/student orhttp://localhost/student/index is handled by the Index () method of StudentController class, shown above. So let's invoke it from the browser and you will see the following page in the browser.

    Controller

    Action Methods:

    mailto:[email protected]://www.knackhook.com/http://www.tutorialsteacher.com/Content/images/mvc/mvc-controller-5.png

  • 19 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    All the public methods of a Controller class are called Action methods. They are like any other normal methods with the following restrictions:

    1. Action method must be public. It cannot be private or protected 2. Action method cannot be overloaded 3. Action method cannot be a static method.

    The following is an example of Index action method of StudentController

    Action Method As you can see in the above figure, Index method is a public method and it returns ActionResult using the View() method. The View() method is defined in the Controller base class, which returns the appropriate ActionResult.

    Default Action method:

    Every controller can have default action method as per configured route in RouteConfig class. By default, Index is a default action method for any controller, as per configured default root as shown below.

    Default Route:

    routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}/{name}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });

    However, you can change the default action name as per your requirement in RouteConfig class.

    Result Class Description

    mailto:[email protected]://www.knackhook.com/http://www.tutorialsteacher.com/Content/images/mvc/action-method.png

  • 20 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    ActionResult:

    MVC framework includes various result classes, which can be return from an action method. There result classes represent different types of responses such as html, file, string, json, javascript etc. The following table lists all the result classes available in ASP.NET MVC.

    The ActionResult class is a base class of all the above result classes, so it can be return type of action methods which returns any type of result listed above. However, you can specify appropriate result class as a return type of action method.

    The Index() method of StudentController in the above figure uses View() method to return ViewResult (which is derived from ActionResult). The View() method is defined in base Controller class. It also contains different methods, which automatically returns particular type of result as shown in the below table.

    ViewResult Represents HTML and markup.

    EmptyResult Represents No response.

    ContentResult Represents string literal.

    FileContentResult/ FilePathResult/ FileStreamResult

    Represents the content of a file

    JavaScriptResult Represent a JavaScript script.

    JsonResult Represent JSON that can be used in AJAX

    RedirectResult Represents a redirection to a new URL

    RedirectToRouteResult Represent another action of same or other controller

    PartialViewResult Returns HTML from Partial view

    HttpUnauthorizedResult Returns HTTP 403 status

    Result Class Description Base Controller method

    ViewResult Represents HTML and markup. View()

    EmptyResult Represents No response.

    ContentResult Represents string literal. Content()

    FileContentResult, FilePathResult, FileStreamResult

    Represents the content of a file File()

    JavaScriptResult Represent a JavaScript script. JavaScript()

    JsonResult Represent JSON that can be used in AJAX Json()

    RedirectResult Represents a redirection to a new URL Redirect()

    RedirectToRouteResult Represent another action of same or other controller

    RedirectToRoute()

    PartialViewResult Returns HTML PartialView()

    HttpUnauthorizedResult Returns HTTP 403 status

    mailto:[email protected]://www.knackhook.com/

  • 21 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    As you can see in the above table, View method returns ViewResult, Content method returns string, File method returns content of a file and so on. Use different methods mentioned in the above table, to return different types of results from an action method.

    Action method Parameters:

    Every action method can have input parameters as normal methods. It can be primitive data type or complex type parameters as shown in the below example.

    Example: Action method parameters

    [HttpPost] public ActionResult Edit(Student std) { // update student to the database return RedirectToAction("Index"); } [HttpDelete] public ActionResult Delete(int id) { // delete student from the database whose id matches with specified id return RedirectToAction("Index"); } Action method parameters can be Nullable type. By default, the values for action method parameters are retrieved from the request's data collection. The data collection includes name/values pairs for form data or query string values or cookie values. Model binding in ASP.NET MVC automatically maps the URL query string or form data collection to the action method parameters if both names are matching. Visit model binding section for more information on it.

    Action Result Type:

    There are different types of results that are available to you in ASP.NET MVC. When creating new controllers, they will come with one or more actions by default. The Empty controller includes an Index action with a return value of type ActionResult. ActionResult class is the base class for all action results. There are different ActionResult types are there, briefly explained below.

    Action Results Listing:

    View():- It represents an ASP.NET MVC view i.e. when you return HTML to the browser and it is the most common ActionResult returned by a Controller.

    PartialView():- A fragment of an ASP.NET MVC view.

    mailto:[email protected]://www.knackhook.com/

  • 22 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    RedirectToAction():- Redirect from one controller action to a second controller action. Possible parameters that you can use with the RedirectToAction() methods are

    actionName: The name of a controller action. controllerName: Name of a Controller. routeValues: The values passed to the action.

    E.g.:

    return RedirectToAction("Index",Testing);

    return RedirectToAction("Testing2", new {id="2"});

    The RedirectToAction() method returns a 302 found HTTP status code to the browser to perform the redirect to the new action.One advantage of performing a browser redirect is that it updates the browser address bar with the new URL. The disadvantage is that a browser must do a second request.

    Redirect():- Redirection to another controller action or URL. Content():- Raw content sent to the browser. There are multiple overloads of the Content() method. All

    the parameters are mentioned below that you can pass as an argument string: The string to render to the browser. contentype: The MIME type of the content (defaults to text/html). contentEncoding: The text encoding of the content (e.g.: -Unicode or ASCII)

    Json():- JavaScript object Notation (JSON) was invented by Douglas Crockford as a lightweight alternative to XML appropriate for sending data across the internet in Ajax application. E.g: - You can convert a set of database records into a JSON representation and pass the data from the server to the browser. The Json() method uses a class in the .NET framework called the JavaScriptSerializer to serialize an object into a JSON representation. public ActionResult List() { var val = new List { "AAA", "BBB", "CCC" }; return Json(val);

    }

    JSON representation :- ["AAA","BBB","CCC"]

    Json() method has several overloads and supports the following parameters are

    data: The content to serialize. contentType: The MIME type of the content (default to application/json).

    mailto:[email protected]://www.knackhook.com/

  • 23 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    contentEncoding: The text encoding of the content(e.g. Unicode or ASCII). File():- Return a file from an action. E.g.: image file, word file etc. This method accepts the following

    parameters which are mentioned here: filename, contentType, fileDownloadName, fileContents [instead of providing the path to the file to download, you can provide the actual file contents as a byte array], fileStream.

    JavaScript():- Represents a JavaScript file.

    Action Selectors

    Action selector is the attribute that can be applied to an action method in a controller and are used to control or influence which action method gets invoked. It helps routing engine to select the correct action method to handle a particular request.

    MVC 5 includes the following action selector attributes:

    1. ActionName Selector 2. NonAction Selector 3. ActionVerbs Selector

    mailto:[email protected]://www.knackhook.com/

  • 24 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    ActionName Selector

    ActionName attribute allows us to specify a different action name than the already given method name. Consider the following example.

    Example: ActionName

    public class StudentController : Controller { public StudentController() { } [ActionName("find")] public ActionResult GetById(int id) { // get student from the database return View(); } } In the above example, we have applied ActioName("find") attribute to GetById action method. So now, action name is "find" instead of "GetById". This action method will be invoked on http://localhost/student/find/1 request instead of http://localhost/student/getbyid/1 request.

    NonAction:

    NonAction selector attribute indicates that a public method of a Controller is not an action method. Use NonAction attribute when you want public method in a controller but do not want to treat it as an action method.

    For example, the GetStudent() public method cannot be invoked in the same way as action method in the following example.

    Example: NonAction

    public class StudentController : Controller { public StudentController() { } [NonAction] public Student GetStudnet(int id) { return studentList.Where(s => s.StudentId == id).FirstOrDefault(); }

    mailto:[email protected]://www.knackhook.com/

  • 25 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    }

    ActionVerbs:

    The ActionVerbs selector is used when you want to control the selection of an action method based

    on a Http request method. For example, you can define two different action methods with the same name but one action method responds to an HTTP Get request and another action method responds to an HTTP Post request.

    MVC framework supports different ActionVerbs, such as HttpGet, HttpPost, HttpPut, HttpDelete, HttpOptions & HttpPatch. You can apply these attributes to action method to indicate the kind of Http request the action method supports. If you do not apply any attribute, then it considers it a GET request by default.

    The following figure illustrates the HttpGET and HttpPOST action verbs.

    The following table lists the usage of http methods:

    Http method

    Usage

    GET To retrieve the information from the server. Parameters will be appended in the query string.

    mailto:[email protected]://www.knackhook.com/

  • 26 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    POST To create a new resource.

    PUT To update an existing resource.

    HEAD Identical to GET except that server do not return message body.

    OPTIONS OPTIONS method represents a request for information about the communication options supported by web server.

    DELETE To delete an existing resource.

    PATCH To full or partial update the resource.

    The following example shows different action methods supports different ActionVerbs:

    Example: ActionVerbs

    public class StudentController : Controller { public ActionResult Index() { return View(); } [HttpPost] public ActionResult PostAction() { return View("Index"); } [HttpPut] public ActionResult PutAction() { return View("Index"); } [HttpDelete] public ActionResult DeleteAction() { return View("Index"); } [HttpHead] public ActionResult HeadAction() {

    mailto:[email protected]://www.knackhook.com/

  • 27 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    return View("Index"); } [HttpOptions] public ActionResult OptionsAction() { return View("Index"); } [HttpPatch] public ActionResult PatchAction() { return View("Index"); } }

    You can also apply multiple http verbs using AcceptVerbs attribute. GetAndPostAction method supports both, GET and POST ActionVerbs in the following example:

    Example: AcceptVerbs

    [AcceptVerbs(HttpVerbs.Post | HttpVerbs.Get)] public ActionResult GetAndPostAction() { return RedirectToAction("Index"); }

    Action Filters

    Action filters are attributes that can be applied either on a controller action method or on a controller. When applied at the controller level, they are applicable for all actions within that controller. Action filters allow us to add, pre and post processing logic to an action method. This means, they allow us to modify the way in which an action is executed. The ASP.NET MVC framework includes several action filters:

    1. Authorize

    2. ChildActiononly

    3. HandleError

    4. OutputCache

    mailto:[email protected]://www.knackhook.com/

  • 28 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    5. RequireHttps

    6. Validatelnput

    7. ValidateAntiForgeryToken

    Authorize

    In ASP. NET MVC, by default, all the controller action methods are accessible to both anonymous and authenticated uses. If you want action methods to be available only for authenticated and authorized users, then use Authorize attribute. AllowAnonymous Attribute: AllowAnonymous attribute is used to skip authorization enforced by Authorize attribute. Example: Authorize

    [Authorize] public class Homecontroller : Controller { [Allowanonymous] public ActionResult NonSecureMethod() { Return View(); } public ActionResult SecureMethod() { return View(); } }

    ChildActiononly

    Any action method that is with [ChildActionOnly] attribute is a child action method.

    Child action methods will not respond to URL request. If an attempt is made, a runtime error will be thrown stating- Child action is accessible only by a child request.

    Child action methods can be invoked by making child request from a view using "Action()" and RenderAction()" html helpers.

    mailto:[email protected]://www.knackhook.com/

  • 29 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    Example: Authorize

    public class HomeController : Controller { public ActionResult Index() { return View(); } [ChildActionOnly] public ActionResult Countries(List countryData) { return View(); } }

    An action method doesn't need to have [ChildActionOnly] attribute to be used as a child action, but use this attribute to prevent if you want to prevent the action method from being invoked as a result of a user request. Child actions are typically associated with partial views, but this is not compulsory. Child action methods are different from NonAction methods, in that NonAction methods cannot be invoked usingAction() or RenderAction() helpers. Using child action methods, it is possible to cache portions of a view. This is the main advantage of child action methods.

    HandleError

    HandleError Attribute is to display friendly error pages when there is an unhandled exception. To enable custom error pages in MVC

    1. Tun on CustomErrors in Web.Config.

    2. Add Error.cshtml view to the “Shared” folder. 3. Add HandleError Attribute to the GlobalFilters collection in global.asax. When a filter is added to

    the GlobalFilters collection then it is applicable for all controllers and their action methods in the entire application.

    Protected void Application_Start() {

    mailto:[email protected]://www.knackhook.com/

  • 30 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes);

    }

    By default friendly error page is not displayed for HTTP status code 404. To display we have follow these steps

    1. Add “ErrorController” to the controllers folder

    Public class ErrorController : Controller {

    Public ActionResult NotFound() { return View(); }

    }

    2. Add NotFound.cshtml to the “Shared” folder 3. Change “customErrors” element in web.config as shown below

    OutputCache

    OutputCache Attribute is used to cache the content returned by a controller action method, so that, the same content does not need to be generated each and every time the same controller action is invoked. Example: OutputCache //Output Of the Index() action method will be cached for 10 Second • [OutputCache(Duration = 10)] public ActionResult Index() { return View(db.Employees.ToList()); } //Child actions can be used to implement partial caching, although not necessary. In this case, even if the ChildActionOnly attribute is removed a portion of the view is cached as expected. [ChlidActionOnly] [OutputCache(Duration = 10)] public string GetEmployeeCount() {

    mailto:[email protected]://www.knackhook.com/

  • 31 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    return "Employee Count = “ + db.Employees.Count().ToString() + “@” + DateTime.Now.ToString(); }

    CacheProfiles in MVC

    To cache the data retuned by Index() action method, for 60 seconds we would use [OutputCache] attribute as shown below. [OutputCache(Duration = 60)] public ActionResult Index() { return View(db.Employees.ToList()); }

    As Outpucache setting are specified in code, the following are the disadvantages

    1. If you have to apply the same cache settings, to several methods, then the cade need to be duplicated.

    2. Later, if we have to change these cache settings, then we need to change them at several places. Maintaining the code becomes complicated. Also, changing the application code requires build and re-deployment.

    To overcome these disadvantages, cache setting can be specified in web.config file using cache profiles. Step 1: Specify cache settings in web.config using cache profiles

    Step 2: Reference the cache profile in application code [OutputCache(CacheProfile=”1MinuteCache”)] public ActionResult Index() { return View(db.Employees.ToList()); }

    mailto:[email protected]://www.knackhook.com/

  • 32 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    The cache settings are now read from one central location i.e from the web.config file. The advantage of using cache profiles is that 1. You have one place to change the cache settings. Maintainability is much easier. 2. Since the changes are done in web.config, we need not build and redeploy the application. Using Cache profiles with child action methods: [ChildActionOnly] public string GetEmployeeCount() { return "Employee Count = “ + db.Employees.Count().ToString() + “@” + DateTime.Now.ToString(); } When Cache profiles are used with childaction methods, you will get an error- Duration must be a positive number To make cache profile work with child action methods, create a custom OutputCache attribute. Public class PartialCacheAttribute : OutputCacheAttribute { public PartialCacheAttribute(string cacheProfileName) { OutputcacheSettingsSection cacheSettings = (OutputCacheSettingsSection)WebConfigurationManager.GetSection( "system.web/caching/outputCacheSettings"); OuttputCacheProfile cacheProfile = cacheSettings.OutputCacheProfiles[cacheProfileName]; Duration = cacheProfile.Duration; VaryByParam = cacheProfile.VaryByParam; VaryByCustom = cacheProfile.VaryByCustom; } }

    Use PartialCacheAttribute on the child action method, and pass it the name of the cache profile in web.config. [ChildActionOnly] [PartialCache(”1MinuteCache”)] public string GetEmployeeCount() {

    mailto:[email protected]://www.knackhook.com/

  • 33 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    return "Employee Count = “ + db.Employees.Count().ToString() + “@” + DateTime.Now.ToString(); }

    RequireHttps

    RequireHttps attribute forces an unsecured HTTP request to be re-sent over HTTPS. [RequireHttps] public String Login() { return "This Should be accessed only using HTTPS protocol"; }

    RequireHttps attribute can be applied on a controller as well. In this case, it is applicable for all action methods with in that controller. Sensitive data such as login credentials, credit card information etc, must always be transmitted using HTTPS. Information transmitted over https is encrypted.

    Validatelnput

    ValidateInput attribute is used to enable or disable request validations. By default, validation is enabled in ASP.NET MVC and does not allow you to submit any HTML, to prevent XSS(Cross site scripting attacks).

    mailto:[email protected]://www.knackhook.com/

  • 34 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    XSS : Cross site scripting attack also called as XSS attack, is a security vulnerability found in Web applications. XSS allows hackers to inject client side script into Web pages, and later, if that web page is viewed by others, the stored script gets executed. The consequences of XSS may range from a petty nuisance like displaying an alert() box to a significant security risk, like stealing session cookies.

    ValidateAntiForgeryToken

    MVC's anti-forgery support writes a unique value to an HTTP-only cookie and then the same value is written to the form. When the page is submitted, an error is raised if the cookie value doesn't match the form value.

    It's important to note that the feature prevents cross site request forgeries. That is, a form from another site that posts to your site in an attempt to submit hidden content using an authenticated user's credentials. The attack involves tricking the logged in user into submitting a form. The feature doesn't prevent any other type of data forgery or tampering based attacks. To use it, decorate the action method or controller with the ValidateAntiForgeryToken attribute and place a call to @Html.AntiForgeryToken() in the forms posting to the method.

    Example : ValidateAntiForgeryToken

    [HttpPost] [ValidateAntiForgeryToken] public ActionResult CreateProduct(Product product) { if (ModelState.IsValid) { //code } return View(ModelName); }

    It is derived from System.web.mvc namespace

    And in view, add this code to add the token so it is used to validate the form upon submission “@Html.AntiForgeryToken()” .

    Types of filters in MVC

    There are 4 types of filters in ASP.NET MVC 1. Authorization filters- Implements IAuthorizationFilter. Examples include AuthorizeAttribute and RequireHttpsAttribute. These filters run before any other filter. 2. Action filters – Implement IActionFilter 3. Result Filters - Implements IResultFilter. Examples include OutPutcacheAttribute. 4. Exception filters - Implement IExceptionFilter. Examples include HandleErrorAttribute.

    mailto:[email protected]://www.knackhook.com/

  • 35 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    Views

    View is a user interface. View displays data from the model to the user and also enables them to modify the data.

    ASP.NET MVC views are stored in Views folder. Different action methods of a single controller class can render different views, so the Views folder contains a separate folder for each controller with the same name as controller, in order to accommodate multiple views.

    For example, views, which will be rendered from any of the action methods of HomeController, resides in Views > Home folder. In the same way, views which will be rendered from StudentController, will resides in Views > Student folder

    ASP.NET MVC application, incoming browser requests are mapped to controller actions. A controller action might return a view. However, a controller action might perform some other type of action such as redirecting you to another controller action.

    Listing 1 contains a simple controller named the HomeController. The HomeController exposes two controller actions named Index() and Details().

    Listing 1 - HomeController.cs using System.Web.Mvc; namespace MvcApplication1.Controllers { [HandleError] public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult Details() { return RedirectToAction("Index"); } } }

    You can invoke the first action, the Index() action, by typing the following URL into your rowser address bar:

    /Home/Index

    You can invoke the second action, the Details() action, by typing this address into your browser:

    mailto:[email protected]://www.knackhook.com/

  • 36 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    /Home/Details

    The Index() action returns a view. Most actions that you create will return views. However, an action can return other types of action results. For example, the Details() action returns a RedirectToActionResult that redirects incoming request to the Index() action.

    The Index() action contains the following single line of code:

    View();

    This line of code returns a view that must be located at the following path on your web server:

    \Views\Home\Index.aspx

    The path to the view is inferred from the name of the controller and the name of the controller action.

    If you prefer, you can be explicit about the view. The following line of code returns a view named Fred :

    View( Fred );

    When this line of code is executed, a view is returned from the following path:

    \Views\Home\Fred.aspx

    If you plan to create unit tests for your ASP.NET MVC application, then it is a good idea to be explicit about view names. That way, you can create a unit test to verify that the expected view was returned by a controller action.

    Adding Content to a View

    A view is a standard (X)HTML document that can contain scripts. You use scripts to add dynamic content to a view.

    For example, the view in Listing 2 displays the current date and time.

    Listing 2 - \Views\Home\Index.aspx Index

    mailto:[email protected]://www.knackhook.com/

  • 37 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    The current date and time is

    Notice that the body of the HTML page in Listing 2 contains the following script:

    You use the script delimiters to mark the beginning and end of a script. This script is written in C#. It displays the current date and time by calling the Response.Write() method to render content to the browser. The script delimiters can be used to execute one or more statements.

    Since you call Response.Write() so often, Microsoft provides you with a shortcut for calling the Response.Write() method. The view in Listing 3 uses the delimiters as a shortcut for calling Response.Write().

    Listing 3 - Views\Home\Index2.aspx Index The current date and time is @DateTime.Now You can use any .NET language to generate dynamic content in a view. Normally, you’ll use either Visual Basic .NET or C# to write your controllers and views.

    Using HTML Helpers to Generate View Content

    mailto:[email protected]://www.knackhook.com/

  • 38 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    To make it easier to add content to a view, you can take advantage of something called an HTML Helper. An HTML Helper, typically, is a method that generates a string. You can use HTML Helpers to generate standard HTML elements such as textboxes, links, dropdown lists, and list boxes.

    For example, the view in Listing 4 takes advantage of three HTML Helpers -- the BeginForm(), the TextBox() and Password() helpers -- to generate a Login form (see Figure 1).

    Listing 4 -- \Views\Home\Login.aspx Login Form @using (Html.BeginForm()) { User Name:
    @Html.TextBox("UserName")

    Password:
    @Html.Password("Password")

    }

    mailto:[email protected]://www.knackhook.com/

  • 39 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    Figure 01: A standard Login form

    All of the HTML Helpers methods are called on the Html property of the view. For example, you render a TextBox by calling the Html.TextBox() method.

    Notice that you use the script delimiters when calling both the Html.TextBox() and Html.Password() helpers. These helpers simply return a string. You need to call Response.Write() in order to render the string to the browser.

    Using HTML Helper methods is optional. They make your life easier by reducing the amount of HTML and script that you need to write. The view in Listing 5 renders the exact same form as the view in Listing 4 without using HTML Helpers.

    Listing 5 -- \Views\Home\Login.aspx Login Form without Help

    mailto:[email protected]://www.knackhook.com/http://az601479.vo.msecnd.net/v-2015-11-24-001/asp.net/images/mvc/4_new/image001.png

  • 40 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    User Name:


    Password:


    You also have the option of creating your own HTML Helpers. For example, you can create a GridView() helper method that displays a set of database records in an HTML table automatically. We explore this topic in the tutorial Creating Custom HTML Helpers.

    Using View Data to Pass Data to a View

    You use view data to pass data from a controller to a view. Think of view data like a package that you send through the mail. All data passed from a controller to a view must be sent using this package. For example, the controller in Listing 6 adds a message to view data.

    Listing 6 - ProductController.cs using System.Web.Mvc; namespace MvcApplication1.Controllers { public class ProductController : Controller { public ActionResult Index() { ViewData["message"] = "Hello World!"; return View(); } } } The controller ViewData property represents a collection of name and value pairs. In Listing 6, the Index() method adds an item to the view data collection named message with the value Hello World! . When the view is returned by the Index() method, the view data is passed to the view automatically.

    mailto:[email protected]://www.knackhook.com/

  • 41 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    The view in Listing 7 retrieves the message from the view data and renders the message to the browser.

    Listing 7 -- \Views\Product\Index.aspx

    Product Index @Html.Encode(ViewData["message"])

    Notice that the view takes advantage of the Html.Encode() HTML Helper method when rendering the message. The Html.Encode() HTML Helper encodes special characters such as < and > into characters that are safe to display in a web page. Whenever you render content that a user submits to a website, you should encode the content to prevent JavaScript injection attacks.

    In Listing 7, we took advantage of view data to pass a simple string message from a controller to a view. You also can use view data to pass other types of data, such as a collection of database records, from a controller to a view. For example, if you want to display the contents of the Products database table in a view, then you would pass the collection of database records in view data.

    You also have the option of passing strongly typed view data from a controller to a view.

    View engines

    View Engine renders the HTML to the browser. The view engine templates have a different syntax than the implementation. By default, ASP.Net MVC supports ASPX and the Razor View Engine. There are many more third-party view engines, like Spark, Nhaml and so on also available for MVC. We can also write our own view engine.

    Aspx View Engine

    mailto:[email protected]://www.knackhook.com/

  • 42 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    The syntax used for writing a view with the ASPX View Engine is the same as the syntax used in ASP.Net web forms. The file extensions are also the same as for ASP.NET web forms (like .aspx, .ascx, .master).

    This view engine is the default view engine for MVC 1.0 and MVC 2.0. Implementing the unit testing framework with the ASPX View Engine is very difficult.

    ASPX uses "" or "" to render server-side content. We can choose any language with the CodeDom provider. There are on demand or precompiled views supported by an ASPX View Engine.

    The ASPX View Engine is also known as the Web Form View Engine. Loop and condition example with ASPX View Engine:

    is in stock

    is not in stock

    Razor View Engine

    Razor is not a new programming language itself, but uses C# syntax for embedding code in a page without the ASP.NET delimiters: . It is a simple-syntax view engine and was released as part of ASP.NET MVC 3.

    The Razor file extension is "cshtml" for the C# language. It supports TDD (Test Driven Development) because it does not depend on the System.Web.UI.Page class.

    Razor Syntax

    To understand the Razor View Engine we should learn its syntax so let's start with the syntax.

    1. Single statement block and inline expression Each code block will be start and end by opening and closing curly brackets {..} respectively. A statement is defined in a code block, in other words between opening and closing curly brackets and

    mailto:[email protected]://www.knackhook.com/

  • 43 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    ending with a semicolon (";"). But when it's used as an inline expression then it does not need to use a semicolon.

    Here we declare "message" as a variable and assigned a string to it and this variable is accessible globally with the "@" character. So the "@" character is used in both cases when we define a code block as well as a variable call and we get output as below.

    2. Multi statement block We can also define a multiline statement block as a single-line statement block. In a multiline statement block we can define multiple code statements and can process data. A multiline block will exist between opening and closing curly braces but the opening brace will have the "@" character in the same line if we define the "@" and opening curly braces in different lines then it will generate an error.

    Each statement will be endded by a semicolon in a multi-statement code block so finally we get the result as:

    mailto:[email protected]://www.knackhook.com/

  • 44 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    3. Conditional statements We can create a dynamic web page in Razor View Engine as condition based. We can define a condition inside a code block or outside the code block. The If statement works the same as it does in other programming languages.

    It is a default rule that a block statement or statements must exist within curly braces even if the block has a single statement. In the code block above we have two types of if conditions, one is inside code block so the @ character is used with code blocks starting braces and another is outside the code block so the @character is used with an if. Finally, we get the output of these two if statements.

    mailto:[email protected]://www.knackhook.com/

  • 45 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    4. Looping All loops work the same as in other programming languages, we can define looping inside a code or outside a code block. We can define a for, do while or while loop in a code block and use the same syntax for initialization, increment/decrement and to check a condition.

    We can also define a foreach in a code block that accesses data forwardly from any collection. The code block above has both for and foreach statements and their output is:

    mailto:[email protected]://www.knackhook.com/

  • 46 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    5. Comments Razor View Engine has two types of comments, one is single-line and another is multiline. Razor uses the syntax "@* ..*@" for the comment block but in a C# code block we can also use "/* */" or "//". HTML comments are the same, "".

    6. Use of Object We can also use an object in both a code block and HTML using razor syntax.

    mailto:[email protected]://www.knackhook.com/

  • 47 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    Here we used a Date object of the C# language and access the properties of its. The result of the Date object in code above is:

    So we have a rule of thumb that C# code is used in a code block that starts with "@{" and ends with "}" and whenever a variable is used in a HTML block then the variable is used with the prefix "@".

    It is not a complete list of razor syntax but I think that you now have the basic syntax of razor so we should proceed to an example.

    Data Transfer in MVC

    We can transfer the data from Controller to View or pass data between actions of a controller.

    Model

    The best and recommended way to pass the data from a Controller to View is by using Model classes. If we create a strongly typed view than that view is capable of accessing the object/model that is being passed to it from the controller. So for most cases where we need to use some data we should create strongly typed views and pass on Model objects to the views.

    Now when we talk about Model classes there are three main type of Model classes. First are the entities that represent our data model. Second are the classes that represent the domain model of our

    mailto:[email protected]://www.knackhook.com/

  • 48 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    application. Now from an application perspective we will mostly be using these domain models in our view so that the application data can be extracted and shown in the views. We could also use the entities directly if there is a need to show the data from data model directly.

    Example:

    Let us first see how we can create a strongly typed view which will display the data that is being passed to it from the controller. Lets have a simple Model like:

    public class Book { public int ID { get; set; } public string BookName { get; set; } public string Author { get; set; } public string ISBN { get; set; }

    }

    Now let us create a simple Action called SampleBook and create a book object in it and then pass it on to the view.

    public ActionResult SampleBook() { Book book = new Book { ID = 1, BookName = "Sample Book", Author = "Sample Author", ISBN = "Not available" }; return View(book); }

    Now lets add a strongly typed View for this action which will use Book model to retrieve the data. Lets also use the "Details" scaffold so that we don't have to write the code to access the data from the model(just for the demonstration purpose).

    mailto:[email protected]://www.knackhook.com/

  • 49 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    Now if we look at the code for the View we can see that the data is being extracted from the Model which is an object of Book type passed from the controller.

    mailto:[email protected]://www.knackhook.com/

  • 50 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    When we run the application:

    ViewModel

    mailto:[email protected]://www.knackhook.com/

  • 51 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    Now consider a scenario where we need to create a view which needs data from two or more classes/models. How can we create a strongly type view that can extract data from two models. The answer to this is that we cannot. But we can create a new class that can contain these classes' objects in it and this class can be passed as the model class to the view. Now this class is created to be used as model on some views. All such classes are called as ViewModels.

    Example:

    Now let us say we need a View that should display the data from multiple models. Lets say we have one more class which is getting some custom message and it should be displayed on the page whenever a Book data is being displayed. Now this message data is contained in a separate model as:

    public class Message { public string MessageText { get; set; } public string MessageFrom { get; set; } }

    Now we need to pass two objects to the View one Book object and another Message object. Now to do this we need to create a new class i.e. the ViewModel class which will contain these two object in it.

    public class ShowBookAndMessageViewModel { public Book Book { get; set; } public Message Message { get; set; } }

    Now let is create one more action in our controller. This action will create this ViewModel object and pass it to the view.

    public ActionResult SampleBook2() { Book book = new Book { ID = 1, BookName = "Sample Book", Author = "Sample Author", ISBN = "Not available" }; Message msg = new Message { MessageText = "This is a Sample Message", MessageFrom = "Test user" }; ShowBookAndMessageViewModel viewModel = new ShowBookAndMessageViewModel { Message = msg,

    mailto:[email protected]://www.knackhook.com/

  • 52 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    Book = book }; return View(viewModel); }

    Now let us create a strongly typed view that will use this ViewModel class to extract the data.

    And now let us see the code that we need to extract the data from this ViewModel and show it on the View.

    mailto:[email protected]://www.knackhook.com/

  • 53 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    And when we run the application we can see that data can be extracted from this ViewModel class and then corresponding data from Book and Message class and be extracted and shown on the View.

    ViewData and ViewBag

    We saw how Models and ViewModels can be used to pass data from controller to the view. But now consider scenario where we need to pass small amount of data from controllers to view. Now for every such case if we start creating ViewModels then managing these view models will become a nightmare. For all such requirements where we need to transfer small amount of data, we can use Viewdata and ViewBag.

    ViewData

    ViewData is an in built dictionary object that can be accessed and set with string type key values. It is derived from ViewDataDictionary class and is a very handy data structure when it comes to passing data from Controller to View. The data is only alive for one request and cannot persist between request. The

    mailto:[email protected]://www.knackhook.com/

  • 54 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    only problem with ViewData is that the type casting is required for complex data types at the location where the data is being extracted.

    Example:

    We have discussed that the ViewData can be used to pass simple and small data from controller to the view Let is see how we can pass a simple message string from Controller to View using ViewData.

    public ActionResult Index() { ViewData["Message"] = "This Message is coming from ViewData"; return View();

    }

    And now this data can be extracted from the view as:

    And when we run the application:

    Note: We are not type casting the data in view because it is simple string. If this data would have been of some complex type, type casting would become inevitable.

    ViewBag

    mailto:[email protected]://www.knackhook.com/

  • 55 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    C# 4.0 has the possibility of having dynamic Variables. ViewBag data structure has been created to utilize this and is written as a wrapper over the ViewData so that the type casting for complex objects will not be required if we use ViewBag. ViewBag comes with all the benefits of ViewData with an additional benefit that type casting is not required.

    Example:

    Now let us try to implement the same functionality like above but by using ViewBag instead of ViewData.

    public ActionResult Index2() { ViewBag.Message = "This Message is coming from ViewBag"; return View();

    }

    And now this data can be extracted from the view as:

    And when we run the application:

    TempData

    Now the problem with all the above ways of data transfer was that the data is only alive for current request. The data is lost if a redirection takes place i.e. one Action redirects to another action. For the

    mailto:[email protected]://www.knackhook.com/

  • 56 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    scenarios where we need to persist the data between actions/redirection another dictionary object called TempData can be used. It is derived from TempDataDictionary. It is created on top of session. Its will live till the redirected view is fully loaded.

    Example:

    Now let us say we have an action method redirect to another action method and we need to pass some data from one action method to another action method. To do this you we will have to use TempData.

    public ActionResult SampleBook3() { Book book = new Book { ID = 1, BookName = "Sample Book", Author = "Sample Author", ISBN = "Not available" }; TempData["BookData"] = book; return RedirectToAction("SampleBook4"); } public ActionResult SampleBook4() { Book book = TempData["BookData"] as Book; return View(book);

    }

    Now when the SampleBook3 action will be called it will create a Book type, put it in a TempData variable and then redirect to action SampleBook4. Now in SampleBook4, the data will be extracted from the TempDataand then the View for the SampleBook4 will be shown which is a strongly typed view and is capable of showing the data from the Book model.

    Sessions

    Session is the way to persist the data till the current session is alive. If we need some data to be accessible from multiple controllers, actions and views then Session is the way to store and retrieve the data.

    Example:

    Use of sessions has nothing new for the the web developers. We can use session variables to persist the data for a complete session. To demonstrate this let us implement the above functionality using sessions instead ofTempData.

    mailto:[email protected]://www.knackhook.com/

  • 57 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    public ActionResult SampleBook5() { Book book = new Book { ID = 1, BookName = "Sample Book", Author = "Sample Author", ISBN = "Not available" }; Session["BookData"] = book; return RedirectToAction("SampleBook6"); } public ActionResult SampleBook6() { Book book = Session["BookData"] as Book; return View(book); }

    Now when the SampleBook5 action will be called it will create a Book type, put it in a session variable and then redirect to action SampleBook6. Now in SampleBook6, the data will be extracted from the Session and then the View for the SampleBook6 will be shown which is a strongly typed view and is capable of showing the data from the Book model.

    Strongly typed Views

    A strongly typed View is one that is generated or as associated to a Model.

    If you have a model like Student having attributes like: ID, Age, Name. And you have an Action Method like Create in your (Student Controller), your strongly typed view would be a [Create.cshtml] page with fields to enter students age and name.

    Unlike any other plain HTML page, a strongly typed view is generated from a model.

    You can pass an empty model object to this view, populate the object and send it back to the controller. Or

    You could purely use it for displaying records from your database like an Index Page.

    Example:

    When we create a strongly typed view the main benefit is that we can send the data in object form.

    Step 1

    Create the application using the Web API.

    Step 2

    mailto:[email protected]://www.knackhook.com/

  • 58 | P a g e

    KnackHook Knowledge Holder

    [email protected] www.knackhook.com

    Create a Model Class and Add the following Code:

    using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MvcApplication1.Models { public class Employee { public string Name { get; set; } public string Address { get; set; } public string Designation { get; set; } }

    }

    Step 3

    Create a Controller and Add the following code:

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MvcApplication1.Models; namespace MvcApplication1.Controllers { public class EmployeeController : Controller { /


Recommended