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.
- Open Visual Studio.
- Click File > New > Project or press CTRL+SHIFT+N.
- In the installed templates select Web and select ASP.NET MVC 4 Web Application.
- Set the name for the application to something such as "DemoMVC", then click OK.
- Then select "Empty" Template. Select "Razor" as a view engine and click OK.
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:
- In the Solution Explorer, right-click on the "Controllers" folder.
- Select the "Add" menu item and click on the "Controllers" menu item.
- Set the controller name as a "HomeController"and leave other other options as the default.
- 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:
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.
- 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.