ASP.NET MVC – Overview

History
ASP.NET 1.0 was released on January 5, 2002 as part of the .Net Framework version 1.0. At the time, it was easy to think of ASP.NET and Web Forms as the same thing. However, ASP.NET has always supported two levels of abstraction:

System.Web.UI – Web Forms layer, including server controls, ViewState, etc.

System.Web – Provides a basic web stack, including modules, handlers, HTTP stack, etc.

When ASP.NET MVC was announced in 2007, the MVC model had become one of the most popular ways to create webmasters.

In April 2009, the ASP.NET MVC source code was released under the Microsoft Public License (MS-PL). “ASP.NET MVC framework is an easy and highly testable presentation framework, integrated with existing ASP.NET capabilities.

Some of these built-in features are master pages and membership-based authentication. The MVC framework is defined in the System.Web.Mvc assembly.

In March 2012, Microsoft released part of its web stack (including ASP.NET MVC, Razor and Web API) under an open source license (Apache License 2.0). ASP.NET Web Forms was not included in this initiative.

Why ASP.NET MVC?

Microsoft decided to create their own MVC framework for building web applications. The MVC framework simply builds on top of ASP.NET. When you are building a web application with ASP.NET MVC, there will be no illusions of state, there will not be such a thing as a page load and no page life cycle at all, etc.

Another design goal for ASP.NET MVC was to be extensible throughout all aspects of the framework. So when we talk about views, views have to be rendered by a particular type of view engine. The default view engine is still something that can take an ASPX file. But if you don’t like using ASPX files, you can use something else and plug in your own view engine.

There is a component inside the MVC framework that will instantiate your controllers. You might not like the way that the MVC framework instantiates your controller, you might want to handle that job yourself. So, there are lots of places in MVC where you can inject your own custom logic to handle tasks.

The whole idea behind using the Model View Controller design pattern is that you maintain a separation of concerns. Your controller is no longer encumbered with a lot of ties to the ASP.NET runtime or ties to the ASPX page, which is very hard to test. You now just have a class with regular methods on it that you can invoke in unit tests to find out if that controller is going to behave correctly.

Benefits of ASP.NET MVC

Following are the benefits of using ASP.NET MVC −

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

Enables full control over the rendered HTML and provides a clean separation of concerns.

Direct control over HTML also means better accessibility for implementing compliance with evolving Web standards.

Facilitates adding more interactivity and responsiveness to existing apps.

Provides better support for test-driven development (TDD).

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

ASP.NET MVC – Controllers

  • Controller is a C# Class
  • Process the Request (a. MODEL , b. VIEW)
  • MVC handle can identify a controller class Suffix:Controller
  • Implementing “Controller” Base class
  • Defined under “System.Web.MVC”

Controllers are essentially the central unit of your ASP.NET MVC application. It is the 1st recipient, which interacts with incoming HTTP Request. So, the controller decides which model will be selected, and then it takes the data from the model and passes the same to the respective view, after that view is rendered. Actually, controllers are controlling the overall flow of the application taking the input and rendering the proper output.

Controllers are C# classes inheriting from System.Web.Mvc.Controller, which is the builtin controller base class. Each public method in a controller is known as an action method, meaning you can invoke it from the Web via some URL to perform an action.

The MVC convention is to put controllers in the Controllers folder that Visual Studio created when the project was set up.

Example : EMPLOYEE CONTROLLER

using System;
using System.Collections.Generic;
using System.Linq;

using System.Web;
using System.Web.Mvc;

namespace MVCControllerDemo.Controllers {
public class EmployeeController : Controller {
// GET: Employee
public ActionResult Search(string name){
var input = Server.HtmlEncode(name);
return Content(input);
}
}
}

If you add a parameter to an action method, then the MVC framework will look for the value that matches the parameter name. It will apply all the possible combination to find out the parameter value. It will search in the Route data, query string, etc.

Hence, if you request for /Employee/Mark”, then the MVC framework will decide that I need a parameter with “UserInput”, and then Mark will get picked from the URL and that will get automatically passed.

Server.HtmlEncode will simply convert any kind of malicious script in plain text. When the above code is compiled and executed and requests the following URL http://localhost:61465/Employee/Mark, you will get the following output.

 

ASP.NET MVC – VIEW

A view is used to display data using the model class object. The Views folder contains all the view files in the ASP.NET MVC application.

A controller can have one or more action methods, and each action method can return a different view. In short, a controller can render one or more views. So, for easy maintenance, the MVC framework requires a separate sub-folder for each controller with the same name as a controller, under the Views folder.

1. ViewData
2. ViewBag
3. TempData
4. Session

  1. View Data:
    1. Property Of ControllerBase Class.
    2. System.Web.Mvc
    3.Is of Type ViewDataDictionary
    4.ICollection<string,object>

ViewData.Add(“Key”,Value);
ViewData[“Key”]=Value;

ViewData Is Property of ControllerBase Class.

MVC View Data

2 ViewBag:

  1.  Introduced into MVC from version 3.0
  2. In C#4.0 data type is “dynamic”
  3. Property of ControllerBase class
  4. System.Web.Mvc
  5. Is is of type “dynamic” 
  6. ViewBag.name=value;
  7. Dynamic types are resolved during runtime.
  8. Viewbag can directly return complex values on callback
  9. Viewbag is available only for current request.

Example Given Below.

Public Class DemoController: Controller
{
public ViewResult Index()
{
ViewBag.name=”David”;
ViewBag.categories=new List<string>
{
“Electronics”,
“Shoes”
};
return View();
}
}

 

Index.Chtml

<h2>Index</h2>
Hello ! @ViewBag.name
<h2>Categrories List </h2>

<ol>
@foreach(var item in ViewBag.categories)
{
<li>@item</li>
}
</ol>

Partial ViewResult 

Represents a base class that is used to render a partial view to the response.

  • PartialView is similar to a web User Control
  • It is a reusable prototype that can be accessed and used in any another view.

 

ASP.NET MVC – Actions

Action Methods: Controller Action Methods that respond to various Http Verbs, Like GET,POST,PUT,DELETE….

  • Controller Action Method must be Public in access.
  • it’s can’t be Static.
  • Action Method Return a Value.
  • it Must be defined with a return type.
  • it can’t be void.
  • it can be parameter less or parameterized.
  • it can’t have ref and out parameters.
  • it can’t have open generic types.
  • it can overload.
  • it can’t override.
  • it can’t be any extension method.
  • it can’t be any method of controller base class.
  • it can’t be marked with “NonAction” Attribute.

MVC Action

ASP.NET MVC Action Methods are responsible to execute requests and generate responses to it. By default, it generates a response in the form of ActionResult. Actions typically have a one-to-one mapping with user interactions.

For example, enter a URL into the browser, click on any particular link, and submit a form, etc. Each of these user interactions causes a request to be sent to the server. In each case, the URL of the request includes information that the MVC framework uses to invoke an action method. The one restriction on action method is that they have to be instance method, so they cannot be static methods. Also there is no return value restrictions. So you can return the string, integer, etc.

Types of Action

Actions basically return different types of action results. The ActionResult class is the base for all action results. Following is the list of different kind of action results and its behavior.

Sr.No.

Name and Behavior

1

ContentResult

Returns a string

2

FileContentResult

Returns file content

3

FilePathResult

Returns file content

4

FileStreamResult

Returns file content

5

EmptyResult

Returns nothing

6

JavaScriptResult

Returns script for execution

7

JsonResult

Returns JSON formatted data

8

RedirectToResult

Redirects to the specified URL

9

HttpUnauthorizedResult

Returns 403 HTTP Status code

10

RedirectToRouteResult

Redirects to different action/different controller action

11

ViewResult

Received as a response for view engine

12

PartialViewResult

Received as a response for view engine

ASP.NET MVC – Filters

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

To support this, ASP.NET MVC provides filters. Filters are custom classes that provide both a declarative and programmatic means to add pre-action and post-action behavior to controller action methods.

Action Filters
An action filter is an attribute that you can apply to a controller action or an entire controller that modifies the way in which the action is executed. The ASP.NET MVC framework includes several action filters −

OutputCache − Caches the output of a controller action for a specified amount of time.

HandleError − Handles errors raised when a controller action is executed.

Authorize − Enables you to restrict access to a particular user or role.

Types of Filters

The ASP.NET MVC framework supports four different types of filters −

Authorization Filters − Implements the IAuthorizationFilter attribute.

Action Filters − Implements the IActionFilter attribute.

Result Filters − Implements the IResultFilter attribute.

Exception Filters − Implements the IExceptionFilter attribute.

Filters are executed in the order listed above. For example, authorization filters are always executed before action filters and exception filters are always executed after every other type of filter.

Authorization filters are used to implement authentication and authorization for controller actions. For example, the Authorize filter is an example of an Authorization filter.

Let’s take a look at a simple example by creating a new ASP.Net MVC project.

Apply Action Filter

An action filter can be applied to either an individual controller action or an entire controller. For example, an action filter OutputCache is applied to an action named Index() that returns the string. This filter causes the value returned by the action to be cached for 15 seconds.

To make this a working example, let’s modify the controller class by changing the action method called Index using the following code.

using System;
using System.Collections.Generic;
using System.Linq;

using System.Web;
using System.Web.Mvc;

namespace MVCFiltersDemo.Controllers {
public class HomeController : Controller{
// GET: Home
[OutputCache(Duration = 15)]

public string Index(){
return “This is ASP.Net MVC Filters Tutorial”;
}
}
}

Let’s add another action method, which will display the current time.

namespace MVCFiltersDemo.Controllers{
public class HomeController : Controller{
// GET: Home

[OutputCache(Duration = 15)]
public string Index(){
return “This is ASP.Net MVC Filters Tutorial”;
}

[OutputCache(Duration = 20)]
public string GetCurrentTime(){
return DateTime.Now.ToString(“T”);
}
}
}