Asp.Net MVC 4 tutorial

This tutorial, we will discuss what is Asp.Net MVC and asp.net mvc4, advantages of Asp.Net MVC, etc. We will also see how to create an asp.net mvc4 application using visual studio and also we will see how to create asp.net MVC4 controller class.

Introduction to Asp Net mvc 4 tutorial

Asp.Net MVC is a web development framework on the Microsoft .NET platform that provides a way for developers to build well-structured web applications. MVC helps in separating the components of a web application which gives you more control in individual parts of the application.

Asp.Net MVC provides an alternative to Web Forms for building web applications on the .NET platform.

Asp.Net MVC 4 works with .NET 4 as well as .NET 4.5.

The MVC pattern helps you create applications that separate the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements.

MVC stands for Model-View-Controller.

Asp.Net mvc 4 tutorial

Model:
Model part of the application that handles the logic for the application data. Sometimes stores and retrieve data from the database. Business logic belongs in the model.

View:
View part of the application handles the display part of data, it displays the application’s user interface (UI). The UI logic belongs in the view.

Controller:
The controller part of the application that handles user interaction. The controller handles and responds to user input and interaction. Input logic belongs in the controller.

In Asp.Net MVC you do not have to work with ASPX pages and controls, postbacks or view state, or page lifecycle events.

Advantages of Asp.Net MVC

Below are few advantages of Asp.Net MVC:

  • MVC 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 provides better support for test-driven development (TDD).
  • Asp.Net MVC provides powerful URL mapping.
  • Asp.Net MVC uses existing Asp.net features like forms authentication and Windows authentication, URL authorization, membership and roles, output and data caching, session and profile state management, health monitoring, the configuration system, and the provider architecture.

MVC Framework VS Classic ASP.NET

It is really a big question whether to use MVC framework or to use classic asp.net. But few point to remember:

The MVC Framework doesn’t support classic postback and viewstate and doesn’t consider any URL as the endpoint to a physical server file to parse and compile to a class. In ASP.NET, you have a 1:1 correspondence between a URL and a resource.

In the MVC Framework, a URL is seen as the mean to address a logical server resource, but not necessarily an ASPX file to parse.

Representational State Transfer, or REST:

REST is an architectural pattern that defines how network resources should be defined and addressed in order to gain shorter response times, clear separation of concerns between the front-end and back-end of a networked system. REST is based on three following principles:

  • An application expresses its state and implements its functionality by acting on logical resources
  • Each resource is addressed using a specific URL syntax
  • All addressable resources feature a contracted set of operations

The MVC Framework fulfills it entirely. But classic asp.net supports the PostBack data model.

Web applications developed with ASP.NET MVC are even more SEO (Search Engine) friendly.

In case of MVC developer has to do more coding.

Create Asp.Net MVC4 application using Visual Studio

Now we will see how to create a sample application using Asp.Net MVC4.

Follow below steps to create a demo asp.net mvc4 application.

Step-1:
Open Visual Studio 2010, then go to File -> New Project. This will open the New Project dialog box. From there make sure .Net Framework 4 is selected. Then select the Visual C# -> Web templates list.

From the web template lists, Select ASP.NET MVC 4 Web Application and give a name as shown in the figure below:

Step-2:
Then from the New Asp.Net MVC Project dialog box select Internet Application. And also chose Razor engine. Also, you can select a unit test project and click on OK. As shown in the figure below:

create asp.net MVC4 application visual studio

Now your demo application is ready.

Asp.Net MVC4 Controller class example

Now, we will see, how to add a controller class in Asp.Net MVC 4 application. Also if you have created an Asp.Net MVC 4 demo using this article, then you will able to see 2 default controllers are there: HomeController.cs and AccountController.cs.

Controllers are responsible for responding to user input, often making changes to the model in response to user input.

Here we will see how we can add a Controller class. Remember every controller class is derived from System.Web.Mvc.Controller.

Follow below steps to add a controller class:

First Right click on the Controller folder then click on Add -> then click on Controller as shown in the figure below:

asp.net MVC4 Controller class

Then this will open the Add Controller dialog box. Thn give a controller name and select the template type, here we have selected Empty MVC Controller and then click on Add as shown in the figure below:

create asp.net MVC4 application

Now you can add a method like below in the controller class like below:

public string WelCome()
{
return "Welcome to MVC World !!!";
}

Now if you want to run like below:

http://localhost:16957/Test/WelCome

Then the output will show like below:

Welcome to MVC World !!!

Filter Attribute in Asp.Net MVC

Here we will discuss Filter Attribute in Asp.Net MVC.

ASP.NET MVC provides a way for us to do that by writing custom filters that can be used to avoid extra processing logic in the request-response cycle.

It will help us to use Some extra logic that is written once and can be reused across multiple controllers and/or actions.

The way we can put the pre-processing and post-processing logic is by decorating the actions with attributes which will invoke an attribute class implementing the logic inside Filter.

For example, when the user clicks any link, a request is routed to the respective controller, and the corresponding action method is called.

The structure will be like below:

[Attribute1]
Controller1
{
[Attribute2]
Action()
{
}
}

Type of filters in asp.net mvc

Basically, there are 4 types of filters are there in MVC.

  • Authorization filter
  • Action filter
  • Result filter
  • Exception filter

1- Authorization filter:
This filter provides authentication and authorization logic. It will be executed before the action gets executed.

To implement this, interface IAuthorizationFilter should be implemented by the custom attribute class.

2- Action filter:
This filter will be called before and after the action starts executing and after the action has executed. You can put your logic inside Filter.

Here to implement this IActionFilter filter interface need to be implemented.

This interface provides us two methods OnActionExecuting and OnActionExecuted. OnActionExecuting will call before the action gets executed and OnActionExecuted will call after the action gets executed.

3- Result filter:
We can use this filter suppose we want some modification to be done in the action’s result.To use this filter we need to implement the IResultFilter interface.

This interface provides us two methods i.e OnResultExecuting and OnResultExecuted.OnResultExecuting will call before the action result gets executed and OnResultExecuted will call after the action result gets executed.

4- Exception filter:
whenever a controller or action of the controller throws an exception that time this filter will invoke.

This is particularly useful when we need custom error logging.IExceptionFilter interface needs to call here. This interface will provide one method OnException.

Note: The order of execution will be like
1- Authorization filter
2- Action filter
3- Result filter
4- Exception filter

Built-in Attributes

ASP.NET MVC provides some of the built-in attribute classes These are as below:

  • AuthorizeAttribute: MVC provides AuthorizeAttribute that is helpful in specifying our custom authorization rules.
  • ActionFilterAttribute: This is the built-in implementation for both IActionFilter and IResultFilter.
  • HandleErrorAttribute: This is the built-in implementation of IExceptionFilter which makes it easier to implement exception handling.

Extension method in Asp.Net MVC

Here we will discuss an important concept i.e Extension method in MVC.

This is a kind of method which will extend the method of a class with out touching the base class as well as with out inheritance.

Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.

Syntax: static Functionname(this classname obj)

For example: There are two modules A and B. In side the Module A there is Class A and Inside Module B, there is class B.In Class A there are method 1(),Method 2(),Method 3() and one newly introduced method i.e Add().

So our aim here is to use the newly introduced method Add() from Class A inside class B in Module B.

Module A
\\\\
Class A
\\\\\
Method 1()
Method 2()
Method 3()
Add()-> Newly introduced method in Class A and Let us assume it is a string type.

Now our aim is to use the newly introduced method Add() in Class B of Module B. So we can use as follows.

Module B
\\\\
Class B
\\\\\
static string Add(this A obj)

Here A is the class name.
the string is the return type.
obj is the object for the respective class A.

Note: You need to add the reference for the respective class from which you are using the method.

Benefits of Extension methods:

  • Extension methods allow existing classes to be extended without depending on inheritance or having to change the class’s source code.
  • If the class is sealed then there is no concept of extending its functionality. For this a new concept is introduced i.e. extension methods.
  • This feature is important for all developers.

Some important tips while using Extension methods:

  • You should define extension method in a top-level static class.
  • The extension method with the same name and signature as an instance method will not be called.
  • Extension methods cannot be used to override existing methods.

What are different types of results in Asp.Net MVC?

Now, we will discuss various results in Asp.Net MVC.

There are so many types of results in MVC. These are given below:

  • ViewResult->Renders a specified View to the response stream.
  • PartialViewResult->Renders a specified partial view to the response stream.
  • EmptyResult->An empty response is returned.
  • RedirectResult->Performs an HTTP redirection to a specified URL.
  • RedirectToRouteResult->Performs an HTTP redirection to a URL that is determined by the routing engine based on given route data.
  • JSONResult->Serialises a given Viewdata object to JSON format.
  • JavaScriptResult->Returns a piece of Javascript code that can be executed on the client.
  • ContentResult->Writes Content to the response stream without requiring a view.T he content result lets you define whatever content you wish to return.
  • FileContentResult->Returns a file from a byte array to the client.
  • FileStreamResult->Returns a file from a stream to the client.
  • FilePathResult->Returns a file from the server’s physical location to the client.

The underlying provider failed on open in entity framework mvc

Now, we will see how to resolve the error: The underlying provider failed on open in entity framework MVC.

To fix the issue follow the below steps:

  • Open the services console Run -> services.msc
  • Find the service Distributed Transaction Coordinator
  • Make sure that this service is started.
  • If the service is not started, right click on the service and select Start

Error: this template attempted to load component assembly NuGet.VisualStudio.Interop in MVC

Recently I got this error while trying to create a MVC 4 project. The error message was: this template attempted to load component assembly NuGet.VisualStudio.Interop, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’. For more information on this problem and how to enable this template, please see documentation on customizing project templates”.

Error: this template attempted to load component assembly NuGet.VisualStudio.Interop in MVC

The error was coming because NuGet is not installed or if it is installed, it is not properly installed.

If NuGet is not installed:

Step-1:
Go to nuget site, and on the home page click on Install NuGet, it will download the NuGet.Tools.vsix, then install it on your Visual Studio 2012.

Step-2:
Once its installed, Restart Visual Studio 2010 again. Now that error should not come.

If NuGet is already installed:

Step-1:
Open Visual Studio 2012, Go to Tools -> Extensions and Updates and then Select NuGet Package Manager and UnInstall this.

Step-2:
Go to nuget site, and on the home page click on Install NuGet, it will download the NuGet.Tools.vsix, then install it on your Visual Studio 2012.

Step-3:
Once its installed, Restart Visual Studio 2010 again. Now that error should not come.

You may like following asp.net mvc tutorials:

This tutorial we learned what is asp.net mvc4, advantages of asp.net mvc. Then we saw how to Create Asp.Net MVC4 application using Visual Studio and then we saw how to create an asp.Net MVC4 Controller class using visual studio.

Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.

Bijay Kumar

I am Bijay from Odisha, India. Currently working in my own venture TSInfo Technologies in Bangalore, India. I am Microsoft Office Servers and Services (SharePoint) MVP (5 times). I works in SharePoint 2016/2013/2010, SharePoint Online Office 365 etc. Check out My MVP Profile.. I also run popular SharePoint web site SPGuides.com

>