Tuesday, 4 February 2014

Creating the first MVC application

Follow the steps as shown and create your hello world mvc application

1.
 Open visual studio
2. Click File > New Project
3. Select "Web" from "Installed Templates" section
4. Select ASP.NET MVC 4 Web Application(If dont have  MVC 4 means then ASP.NET MVC 3) 
5. Set Name="MVCDemo"
6. Click OK
7. Select "Empty" template. Select "Razor" as the ViewEngine. There are 2 built in view engines - Razor and ASPX. Razor is preferred by most mvc developers
8. At this point you should have an mvc application created.

Notice that in the solution explorer, you have several folders - Models, Views, Controllers etc. As the names
 suggest these folders are going to contain Models, Views, and Controllers. 

·         Model , which represents the underlying, logical structure of data in a software application and the high-level class associated with it. This object model does not contain any information about the user interface.
·         View , which is a collection of classes representing the elements in the user interface (all of the things the user can see and respond to on the screen, such as buttons, display boxes, and so forth)
·         Controller , which represents the classes connecting the model and the view, and is used to communicate between classes in the model and view.
Now let's add a controller to our project
1. Right Click on "Controllers" folder
2. Select Add > Controller
3. Set Controller Name = HomeController
4. Leave rest of the defaults and click "Add"
We should have HomeController.cs added to "Controllers" folder. 

At this point run the application by pressing CTRL+F5. Notice that you get an error as shown below.

The First type is as follows
 Right click on the Index() function and Click on "Add View"
Notice that, the view name in "Add View" dialog box matches the name of the controller action method.Select "Razor" as the view engine.Leave the rest of the defaults as is, and click "Add" button.

The Second type is as follows
The following is the function that is automatically added to HomeController class.

public ActionResult Index()
{
    return View();
}
Change the return type of Index() function from "ActionResult" to "string", and return string "Hello from MVC Application" instead of View().

public string Index()
{
    return "Hello from MVC Application";
}

Run the application and notice that, the string is rendered on the screen. When you run the application, by default it is using built-in asp.net development server. In the URL "Home" is the name of the controller and "Index" is the method within HomeController class.
 Finally your first hello world MVC application has been completed

2 comments:

back to top