Click here to Skip to main content
15,860,972 members
Articles / Web Development / ASP.NET

Kicking off with MVC3

Rate me:
Please Sign up or sign in to vote.
4.82/5 (31 votes)
12 Mar 2012CPOL10 min read 42.3K   567   52   16
This article will guide you to create your first MVC3 application

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). 

Image 1

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). 

Image 2 

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. 

Image 3

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”. 

Image 4

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

Image 5 

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”. 

C#
using System.Web.Mvc;
namespace KickOffWithMVC3.Controllers
{
	public class HomeController : Controller
	{
		public string Index()
		{
			return "Hello World";
		}
	}
}  

Rerun the project and you can see the Hello World in the browser.

Image 6 

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

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

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

Image 7 

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”.   

        Image 8

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. 

HTML
@{
	Layout = null;
} 

Change the content of the page to look like below

HTML
@{
	Layout = null;
}
<!DOCTYPE html>
<html>
<head>
	<title>Index</title>
</head>
<body>
	<div style="color:red; font-style:italic">
		Hello world
	</div>
</body>
</html> 

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

Image 9

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.

Update the Index method as follows:-

C#
public ActionResult Index()
{
	ViewBag.DayOfWeek  =  System.DateTime.Now.DayOfWeek;
	return View();
} 

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

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

Image 10 

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

HTML
<p>@Html.ActionLink("Lets check your eligibility here", "Eligibility")</p>  

The above piece of code adds a link to the page “Lets check your eligibility here” and on click of that will call the Eligibility action. When we run the project now we can see this.

Image 11

Once we click on the link we get a 404 error as the “Eligibilty” action is not yet defined. 

Image 12

We can do that by adding the following lines of code in HomeController.cs 

C#
public ActionResult Eligibility()
{
	return View();
}  

Creating Model and adding Validations 

Now what we need is to have a view of this but before doing that lets create a Model class for Eligibility. In order to do that 

Right-click Models on the Solution Explorer and select Add followed by Class from the pop-up menus. 

Image 13 

Give the file name as Eligibile.cs and click the Add button to create the class and edit the file as follows

C#
using System.ComponentModel.DataAnnotations;
namespace KickOffWithMVC3.Models
{
	public class Eligibile
	{
		[Required(ErrorMessage = "Please enter your name")]
		public string Name { get; set; }
		[Required(ErrorMessage = "Please specify your age range")]
		public bool IsEligibleAge { get; set; }
	}
}  

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.

Image 14 

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

C#
@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.

Edit “Index.cshtml” file to have the following content

HTML
@model KickOffWithMVC3.Models.Eligibile
@{
	Layout = null;
}
<!DOCTYPE html>
<html>
<head>
	<title>Eligibility</title>
	<link rel="Stylesheet" href="@Href("~/Content/Site.css")" type="text/css"/>
</head>
<body>
	<div>
		@using (Html.BeginForm())
		{
			@Html.ValidationSummary()
			<p>Your Name : @Html.TextBox("Name")</p>
			<p>Your Age Range : 
				@Html.DropDownList("IsEligibleAge", new[] {
					new SelectListItem() {Text = "Below 18", Value = bool.FalseString},
					new SelectListItem() {Text = "18 and Above", Value = bool.TrueString}
				}, "Please select your age")
			</p>
			<input type="submit" value="Submit Data" />
		}
	</div>
</body>
</html> 

Let’s go through it step by step

The code 

C#
@using (Html.BeginForm())
{	
	...form contents go here...
}   

Is meant to create a form tag which is equivalent to

HTML
<form action="/Home/RsvpForm" method="post">
	...form contents go here...
</form>  

The Code 

 @Html.ValidationSummary()  

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

<input id="Name" name="Name" type="text" value="" />  

Last but not the least the code

Your Age Range : 

@Html.DropDownList("IsEligibleAge", new [] {
	new SelectListItem() {Text = "Below 18", Value = bool.FalseString},
	new SelectListItem() {Text = "18 and Above", Value = bool.TrueString}
}, "Please select your age"

Is meant to create a dropdown to provide options to select age “Below 18 “ and “Above 18” and is equivalent to

<select name="IsEligibleAge">
<option value="">Please select your age</option>
<option value="False">Below 18</option>
<option value="True">18 and Above</option>
</select>

Working with Forms 

Right now when we are clicking on the “Submit” button it just clears the data entered in the form because of post back.

To distinguish between the get and post request we are going to create two different methods as follows:-

C#
[HttpGet]
public ActionResult Eligibility()
{
	return View();
}
[HttpPost]
public ActionResult Eligibility(Eligibile eligibile)
{
	if (ModelState.IsValid)
	{
		return View("ThankYou", eligibile);
	}
	else
	{
		return View();
	}
}

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”

Image 15

Update the content of the body to 

HTML
<body>
    <div>
        <h1>Thank you, @Model.Name</h1>
        @if (Model.IsEligibleAge == true)
        {
           @:Congrats you can cast your vote.
        } 
        else {
           @:Sorry to tell you that you still need to wait until you turn 18 to cast your vote.
        }
    </div>
</body> 

If the age selected is greater than 18 you will get output as "Congrats you can cast your vote." or else "Sorry to tell you that you still need to wait until you turn 18 to cast your vote." 

Now you are all set to done. Hurray we did it. Start playing with the application now :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) 1E
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Varun Sareen8-Apr-13 19:59
Varun Sareen8-Apr-13 19:59 
QuestionMy Vote Of 5 Pin
Adam R Harris2-Jan-13 11:51
Adam R Harris2-Jan-13 11:51 
GeneralMy vote of 5 Pin
majisuman4-Dec-12 23:10
majisuman4-Dec-12 23:10 
GeneralAwesome Pin
demouser74330-Aug-12 22:40
demouser74330-Aug-12 22:40 
QuestionThanks Pin
Gonzalo F.10-Aug-12 5:15
Gonzalo F.10-Aug-12 5:15 
AnswerRe: Thanks Pin
Shashank Bisen10-Aug-12 5:27
Shashank Bisen10-Aug-12 5:27 
BugGood one... A typo Pin
srisaravanan9926-Jun-12 20:56
srisaravanan9926-Jun-12 20:56 
QuestionAbout article Pin
006ashish5-Jun-12 2:30
006ashish5-Jun-12 2:30 
Questiongood article for beingers Pin
Donsw27-May-12 6:33
Donsw27-May-12 6:33 
QuestionVery nice Pin
Phil_Murray21-Mar-12 0:49
Phil_Murray21-Mar-12 0:49 
QuestionI liked your approach. Pin
Paulo Zemek12-Mar-12 9:08
mvaPaulo Zemek12-Mar-12 9:08 
AnswerRe: I liked your approach. Pin
Shashank Bisen12-Mar-12 14:35
Shashank Bisen12-Mar-12 14:35 
QuestionKicking off with MVC3 Pin
EarlNet12-Mar-12 1:44
professionalEarlNet12-Mar-12 1:44 
AnswerRe: Kicking off with MVC3 Pin
Shashank Bisen12-Mar-12 1:46
Shashank Bisen12-Mar-12 1:46 
QuestionGood Effort Pin
Member 39520012-Mar-12 1:18
Member 39520012-Mar-12 1:18 
AnswerRe: Good Effort Pin
Shashank Bisen12-Mar-12 1:28
Shashank Bisen12-Mar-12 1:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.