Monday, April 13, 2015

Creating sample MVC application

Creating an 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
5. Set Name="Sample_MVC"
6. Click OK.
7. Select "Empty" template. 

There are 2 built in view Engines - Razor and ASPX.
 

Select "Razor" as the ViewEngine. 
Razor is preferred by most MVC developers now-a-days. 

Now we have created an mvc application.

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. We will discuss about Models, Views, and Controllers in a later posts.

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.


To fix this error, we need to add a view with name, "Index". We will discuss about views in detail in a later video session. Let's fix it another way. 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 World I am from MVC Sample Application";
}

Run the application and notice that, the string is rendered on the screen.

No comments:

Post a Comment