Introduction

This article is intended to give you a start up with the ASP.NET MVC Framework. I will be explaining things step by step to make you feel comfortable while building your first ASP.NET MVC application. I might have skipped a few details but if you are new to this framework you will still have many interesting things to find out.

Background

If you want to know about the basic of ASP.NET MVC 3 please read this article here, I found this really good.

Creating a New ASP.NET MVC3 Project

Select New Project from the File menu and further select the Web templates now you can see an item called ASP.NET MVC 3 Web Application select it (else you need to install it).

Give a name to your project, I prefer it to be “KickOffWithMVC3” and press the OK button. Now you will get another dialog box, which prompt you to select aiming different types of MVC project templates (Empty, Internet Application and Intranet Application).

If we go for the select “Empty” option it creates a project with the minimum files and folder structures which is needed for your MVC Application, while if we go for “Internet Application” option it creates a small example application that includes features like registration, authentication and navigation. Lastly the “Intranet Application” option which is quite similar to “Internet Application” keeping in mind that the authenticated users use a domain/Active Directory infrastructure.

As it’s going to be a start up article we will try to build things from scratch and hence we select “Empty” option. For the View Engine Dropdown Select “Razor” as it’s a new and improved view engine. Uncheck the “Use HTML5 semantic markup” option and click Ok to create the new project.

Once you are done with it Visual Studio will create a project. Run the application and you will find a 404 error. Stop the application the error shows that we need to do more work in order to run this application.

Working with Controller

Controllers are the heart of the MVC architecture, which handles all the incoming requests. They may look like any other C# class which is being inherited from “System.Web.Mvc.Controller” but its each public method also known as an action method, is meant to invoke a web request through some URL to perform a specific action. As per the convention the best place for controllers is in the controllers folder and hence we are going to follow the same.

In order to add a new controller, right-click the “Controllers” folder in the “Solution Explorer” window and select “Add” and further select “Controller”.

Give the name as “HomeController” obeying the convention that the name of the controllers should end with Controller.

Now click the “Add” button. A new C# file will be created under the “Controller” folder called HomeController.cs. We can clearly see that this class is called “HomeController” and it is derived from “System.Web.Mvc.Controller”.

You can already see an action method name “Index” is created, we are going to modify this method to return “Hello World”.

Routes

Now it's time to understand how things works. In order to do that we need to get the idea of routing system, which decides a particular URL will map to its corresponding controller and action.

By default when an application is created a routing scheme is decided by the Visual Studio which is “/Home/Index”. Meaning if you don’t provide any specific controller and action the Index action of the Home controller will automatically get called. This is defined in “RegisterRoutes” method present in file “Global.asax.cs” of our application. We are not going in depth about changing the default routing in this article. But it nutshell we must understand that if we request any of the following URL’s we are going to invoke the Index action of the Home controller.

•/ •/Home•/Home/Index

Creating and Rendering a View

As we have seen till now the output of our last example was simply a string, but what if we want our output as a Html?

In order to get our result as Html we need follow the below mentioned steps:-

•Modify the Index action

public ActionResult Index()
{
return View();
}

If you run your application at this point of time, you will get the following error page:-

The error method expresses everything by its own, it tries to find out the view at the places mentioned but as Index view can't be found at any of these places. So next step is but obvious that we need to create one.

In order to create a view, right-click on the Index method and select “Add View” on doing this we can see an “Add View” dialog. Unselect all the options and make sure that the View name is “Index”.

Click on the Add button, and we can see a new file called “Index.cshtml” gets created in the “Views/Home” folder, which is one of the locations where Visual Studio was expecting our Index view to be as seen in the error message.

Now if we open the “Index.cshtml” file we can see the following lines followed by some html syntax, for the time being just understand that the lines simply means there is no layout/master page referenced.

Now run your application and you can the the following output in your browser.

This leads to end of your first full fledge MVC3 Application. If you find things interesting and you are keen to learn more, than you can read further else you are done.

Fun with Dynamic Content

In the present world the web application is intended to show dynamic content. In MVC framework, it’s the role of controller to prepare some data and role of view is to render it as output. The data are always passed from the controller to the view.

One of the easiest ways to do it is to use the “ViewBag” object, which is a member of the Controller base class. It is a dynamic object to which we can assign any number of arbitrary properties, which can be passed to the View in order to render it in one way or another.

Here we have created a property of ViewBag named “DayOfWeek ” and assigned it a value (we can give any name to this property).

After this lets update the “Index.cshtml” file to make use of this property and prints “Welcome to the world of dynamic content, today is” followed by the day of the week

<body><divstyle="color:red; font-style:italic">
Welcome to the world of dynamic content, today is @ViewBag.DayOfWeek
</div></body>

Playing with the controls

Now are going to transform this into an application which takes input as you name and age range and tells you whether you are eligible for voting or not. I know it may appear like a simple one but found it sufficient in order to achieve our goals. (We have assumed that if the age of a person is equal to or more than 18 then they can cast thier vote)

In order to do so we will provide user to click on a link which will take them to a page where their eligibility to cast vote can be checked.

So let’s add the following lines of code to the post div tag in “Index.cshtml” file

Here we see two properties Name and IsEligibleAge, the names given to property are self sufficient to explain what does they mean what is new over here is the Required attribute. The Required attributes comes from the namespace “System.ComponentModel.DataAnnotations” and is helpful in putting validations on the fields as its task to make sure that the fields having this property are not empty, there are several other attributes to provide validation in the namespace “System.ComponentModel.DataAnnotations”.

Building Strong Type View

Now it’s time to pay back our attention to the creation of the View, last time we created a normal one so this time let’s try with a strongly typed view.

Right-click inside the “Eligibility” action method and choose Add View to create the view. A new dialog pops up, check the “Create a strongly-typed view” option and select “Eligibile (KickOffWithMVC3.Models)” from the drop-down menu. Uncheck all other options.

Now we ready with our “Eligibility.cshtml” file. At the top of the file we can see the line

@model KickOffWithMVC3.Models.Eligibile

Which states that the model of this class is of KickOffWithMVC3.Models.Eligibile type.

Constructing a Form

Now lets go next by creating a text box to enter a name and a dropdown to select your age range.

Is meant to develop a div to show a validation error message in case of any. In order to style the error message we have used “Site.css” which is already provided in the Content folder while creation of Empty project.

The code

@Html.TextBox("Name")

Is meant to create a TextBox which is binded to the Name property of the Eligibile Model and is equivalent to

The existing Eligibility method is appended with “HttpGet” attribute, which help MVC to decide which method to be called for Get Request. While a new overloaded Eligibility method is appended with “HttpPost” attribute and takes Eligible parameter. We need to import “KickOffWithMVC3.Models” namespace for this.

The code return View("ThankYou", eligibile) may seem to be different, but it just tells to render a view called “ThankYou” and pass eligibile object to it if all the validation cases passes else it return the same view. In order to create this ThankYou view right-click inside the “Eligibility” action method and choose Add View to create the view. A new dialog pops up, check the “Create a strongly-typed view” option and select “Eligibile (KickOffWithMVC3.Models)” from the drop-down menu. Uncheck all other options. Name this view as “ThankYou”