Create Your First ASP.Net MVC Application

Introduction

In my previous article (Get version of your MVC application) we saw how to get your version of your MVC application. Now in this article we will see how to create your own first application using MVC.

The following is the procedure to create your MVC application.

  1. Open Visual Studio.

  2. Click File > New > Project or press CTRL+SHIFT+N.

    create new project

  3. In the installed templates select Web and select ASP.NET MVC 4 Web Application.

  4. Set the name for the application to something such as "DemoMVC", then click OK.

    AddWebApp

  5. Then select "Empty" Template. Select "Razor" as a view engine and click OK.

    AddEmptyApp

At this point your MVC application has been created.

Now notice that in the Solution Explorer, you have several folders and files. There will be the three folders Models, Views, Controllers. As the name suggests, the Models folder contains Models, the Views folder contains Views and the Controllers folder contains Controllers. The following are their purposes:

  • Model: Model is the lowest level of the pattern that maintains the data.

  • View: View is responsible for displaying all or portion of the data in front of users.

  • Controller: Controller interacts among Models and Views.

Now let's add a controller to your project.

Use the following procedure to add a Controller to your project:

  1. In the Solution Explorer, right-click on the "Controllers" folder.

  2. Select the "Add" menu item and click on the "Controllers" menu item.

    AddController

  3. Set the controller name as a "HomeController"and leave other other options as the default.

    ControllerName

  4. After clicking on the Add button in the controllers folder there will be a "HomeControllers.cs" file. It in other words that controller is nothing but a C# code file.

Now if you just press CTRL+F5 and run your project, you will get an error as shown below:

Error

To fix this error you need to add a view to the Views folder with the Name "Index". Here I am not discussing views and I am fixing this error in another way. I am changing the return type of the following action that is automatically added to the HomeController Class.

I am changing the return type of the Index() action from "ActionResult" to "string" type.

Newcode

Code

  1. using System;   
  2. using System.Collections.Generic;   
  3. using System.Linq;   
  4. using System.Web;   
  5. using System.Web.Mvc;   
  6.   
  7. namespace DemoMVC.Controllers   
  8. {   
  9.    public class HomeController : Controller   
  10.    {   
  11.       public string Index()   
  12.       {   
  13.          return "Hello C# Corner. This is My First MVC APP";   
  14.       }   
  15.   
  16.    }   
  17. }   
Now run the file.

Output

Output