Click here to Skip to main content
12,632,959 members (32,689 online)
Click here to Skip to main content
Add your own
alternative version

Stats

17.2K views
22 bookmarked
Posted

Understanding Microsoft ASP.NET MVC Fundamentals

, 21 Aug 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
This article is to help you understand the fundamentals of the Microsoft ASP.NET MVC with basic concepts explained along with code snippets.

Introduction

This article will help you understand the basic fundamentals of popular Microsoft ASP.NET MVC for developing powerful web applications. Its is very essential to get the basics right before you master any technology. This article will help you get started with Microsoft ASP.NET MVC.

What is Microsoft ASP.NET MVC?

Microsoft ASP.NET MVC framework is an extension of Microsoft powerful .NET framework which enables developing powerful web applications. ASP.NET provides an alternative to traditional ASP.NET web development model - ASP.NET Webforms.

ASP.NET MVC provides an architectural approach for developing web applications. The pattern used is popularly known as the MVC design pattern. MVC splits an application into 3 distinct components/layers known as Model, View & Controller.

Purpose of MVC

The primary purpose of the MVC is that each of these layers can be developed and tested independently and then combined together to form a robust application.

Now we will see responsibilities of Model, View and Controller layers.

The Model Layer

  • The Model contains business logic of the application.
  • Model objects implement the logic for application’s data domain.

For example - A Product model object might retrieve information from a database, operate on it, and then write updated information back to a Products table in SQL Server database.

Model File Type: A Class File (.cs extension)

The View Layer

  • The View layer Responsible for interacting with the user
  • View helps visualize the model and communicate with the user
  • Content Type : HTML/JavaScript/CSS
  • Can also render JSON, XML, Custom return types

View File Type: HTML/JavaScript file (.cshtml extension)

The Controller Layer - The Traffic Cop

  • Controls the application flow and interaction between the Model and View
  • Controllers are the Brains of the ASP.NET MVC application. Request the data from the Model Layer.
  • Controller does not perform any of the work directly. Instead, it delegates the work to models and the view layer to do real work

For example: When the user requests some details on the website, the controller asks the model which data is to be shown. Then it passes on this data to the view which generates the HTML which is sent to the client browser.

Controller File Type: Class file (.cs extension)

Note: Controller is neither retrieving the data directly nor generating the HMTL that is to be sent to the browser, but it is only co-ordinating.

The way these 3 layers interact with each other is an attempt to achieve something that we call “Separation of Concerns”. This means that each layer in the same application is ignorant of the functionality of other layers.

They are independent and do not depend on each other to get their work done. Thus, they are Loosely Coupled.

Creating a Sample ASP.NET MVC Application

The default Visual Studio template for creating ASP.NET MVC Web Applications includes an extremely simple sample application that can be used to understand the different parts of an ASP.NET MVC application.

Create a new ASP.NET MVC application with the MVC template by launching Visual Studio and selecting the menu option File -> New -> Project.

In the New Project dialog, select your favorite programming language under Project Types (Visual Basic or C#) and select ASP.NET MVC 3 Web Application under Templates. Click the OK button.

When you create a new ASP.NET MVC application, the New ASP.NET MVC Project dialog appears (see Figure). This dialog enables you to select a project template in your solution - Empty, Internet Application (A default ASP.NET MVC 3 project with an account controller that uses forms authentication), Intranet Application (A default ASP.NET MVC 3 project that uses Windows authentication.). Select the option Internet Application and “Razor” option in the View Engine drop down. Click the OK button. The new Project will be created.

Now let us try to understand the solution explorer and the folders in it that Visual Studio created for us.

Understanding the Solution Explorer

I will explain the folders created by Visual Studio in brief.

Folder

Purpose

Content

Contains the style sheets (.css files) for the demo project.

Controllers

This folder contains the application's sample controllers, which are named AccountController and HomeController. The AccountController class contains login logic for the application. The HomeController class contains logic that is called by default when the application starts.

Models

This is for data-model files.

Scripts

This is used for script files, such as those that support ASP.NET AJAX and jQuery.

Views

This folder contains three subfolders: Account, Home, and Shared. The Account folder contains views that are used as UI for logging in and changing passwords.The Home folder contains an Index view (the default starting page for the application) and an About page view. The Shared folder contains the master-page view for the application.

The sample project we will be creating here is the Auction site.

Creating the Model

Model is nothing but a class with some data. So let us create a model.

To create an Auction Model, just create a class named “Auction” in the Models folder. To do this, right click on the Models folder -> Add -> Class.

A dialog appears. Name the class “Auction” and click Add button. You can now see the “Auction.cs” file created in the Models folder in solution explorer.

Now add some properties that define an auction. These properties will be carrying the Auction data. Your business logic needs to be put here.

Create a class as below:

public class Auction
    {
        public long Id { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public string ImageUrl { get; set; }
        public DateTime StartTime { get; set; }
        public DateTime EndTime { get; set; }
        public decimal StartPrice { get; set; }
        public decimal CurrentPrice { get; set; }
    }

Next, we will see how the controller will put the model into action.

Creating a Controller

We will now see how to expose the model that we created to the world using the Controller. To create a new controller, simply right click the “Controller” folder and under the “Add” menu, select “Controller”.

Give an appropriate name to the controller. Here, we will name it “AuctionsController” (Make sure the suffix “Controller” is there after the Controller name). This controller name will be appearing in the urls by default.

Select “Empty Controller” option under Template drop down. Click Add.

We can see Visual Studio has created a controller with minimum code required to create a Controller. This is a class derived from System.Web.Mvc.Controller class. It also generates a Controller action in the form of “Index” method. This is also known as the Action Method. We can expose this class to the web using this action methods.

This is the minimal code that Visual Studio creates for us inside Auctions Controller.

public class AuctionsController : Controller
{
     // GET: /Auctions/
     public ActionResult Index()
     {
         return View();
     }
 }

Controller actions (here, “Index”) must return some kind of result that will act as a reply to the user. Action methods return result to the view of the same name as that of the action method. Thus, both the Action Name and the View name should be “Index” here.

Now run the site by pressing F5 on your keyboard.

As you have created Index method inside the Auctions Controller, the url to access this page should be “http://localhost:59581/Auctions/Index”.

The url breakup is as below:-

Url: default url/[ControllerName]/[ActionMethod Name]

You can see the action is executed but the ASP.NET complains that it can’t find the view that we have asked it to display – The “Index” View. Thus, the ASP.NET throws a server error. “The view ‘index’ or its master was not found or no view engine supports the searched locations”.

This was expected as we have not yet created the view to be displayed to the user. To fix this, we will now create the view to be displayed.

Creating a View

In the previous step, we saw the error displayed as the Index view did not exist. Kindly note that here we are creating a view that corresponds to the action method in the controller

(The View name and the Controller Action name should be the same. Here, Index() action method and Index View). Thus we create an “Index” View here. To do this, just right click the controller action method that you wish to create a view for and select the “Add View…” option.

A dialog box appears with various options to create a view. But for now, we will keep the default values and proceed. Name the view as “Index” and click Add.

Visual Studio will now create a basic view for us which opens right away. It is in this view that we will add the content that we want to show to the users. Now it just contains a single line of HTML to be displayed. For now, we won’t add anything more to this HTML.

The view is as below:

@{
    ViewBag.Title = "Home Page";
}
<h2>My Index Page</h2>

To see this view in action, run the project by pressing F5 or by clicking the Run in Visual Studio. The project executes to the default url. As we have created the view, we navigate to index viewby entering [ControllerName] / [ActionName or View Name] after the default url.

Here, http://localhost:59581/Auctions/Index.

Now you see the page successfully rendered successfully as the ASP.NET finds the view that we just created. We can verify this view by editing the HTML in the view and then refreshing the view in the browser. The changes are reflected in the view.

Request Routing

Until now, we have seen the Model, View, Controller or the core components of the M-V-C. There is another component which is as important as these components. It is so important that the application cannot function without it. This component is called Routing or Request Routing.

The concept of routing is simple. What it does is to inspect the incoming url to determine which controller action it corresponds to and then pass the execution to that controller action. Other web frameworks expose the path of the page in the url but this is not the case with ASP.NET MVC. This is because it is controller actions and not the web pages that handle the user requests. For this reason, it is important that the routing layer be told how to read the incoming url and map them to correct controller action.

In ASP.NET MVC, this is done when the application first starts up in the Applicaion_Start() method in the “Global.asax.cs” file. The code is as below:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    AuthConfig.RegisterAuth();
}

This method calls the RegisterRoutes() method which adhering to the separation of concerns principle lives in a separate class called “RouteConfig” in the “App_Start” folder. Open RouteConfig to find the RegisterRoutes() method. The code is as below:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home",
        action = "Index", id = UrlParameter.Optional }
    );
}

Routes.IgnoreRoute(): Tells the routing component to ignore any urls that match the given pattern and let the core ASP.NET processing handle them instead.

Routes.MapRoute(): This creates a new route named “Default” as shown in the code and specifies the url pattern that breaks the urls into 3 segments – controller, action and id. Then, we provide some default values for the url segments that we have defined which is used when that particular segment is not provided. In this case, we default to the “Index” action of the “Home” controller and make the “id” parameter optional.

To test this, enter the url which in our case is "http://localhost:59581/Auctions/Index/1".

This takes us to the required view even though we did not enter id in our previous run operations.

Conclusion

Thus, we learnt what is Microsoft ASP.NET MVC and its purpose. We also learnt the responsibilities of the individual components of M-V-C. Then for a hands on feel, we created a sample ASP.NET MVC 3 application alongwith the understanding of the code and the application flow. I hope this helps the readers to get started with ASP.NET MVC by understanding the fundamentals.

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Rajneesh K Barapatre
Software Developer Cybage
India India
No Biography provided

You may also be interested in...

Pro
Pro

Comments and Discussions

 
GeneralMessage Automatically Removed Pin
21-Aug-14 3:37
memberMember 1102722821-Aug-14 3:37 
GeneralRe: essay writing service Pin
Rajneesh K Barapatre21-Aug-14 8:39
memberRajneesh K Barapatre21-Aug-14 8:39 
GeneralVery nice article Pin
Latika surse21-Aug-14 3:16
groupLatika surse21-Aug-14 3:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.161208.2 | Last Updated 21 Aug 2014
Article Copyright 2014 by Rajneesh K Barapatre
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid