Create Your First ASP.Net MVC Application

Introduction

In my previous article (Get the 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: The model is the lowest level of the pattern that maintains the data.
  • View: View is responsible for displaying all or a portion of the data in front of users.
  • Controller: The 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.
    Controllers
  3. Set the controller name as a "HomeController" and leave other other options as the default.
    HomeController
  4. After clicking on the Add button in the controllers folder there will be a "HomeControllers.cs" file. In other words the controller is nothing but a C# code file.
  5. Now if you just press CTRL+F5 and run your project, you will get an error as shown below.
    Error
  6. 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.
  7. I am changing the return type of the Index() action from "ActionResult" to "string" type.
    ActionResult

Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DemoMVC.Controllers
{
    public class HomeController : Controller
    {
        public string Index()
        {
            return "Hello C# Corner. This is My First MVC APP";
        }
    }
}

Now run the file.

Output

Output


Similar Articles