SlideShare a Scribd company logo
MVC :: Creating a Tasklist Application with
ASP.NET MVC
The purpose of this tutorial is to give you a sense of “what it is like” to build an ASP.NET
MVC application. In this tutorial, I blast through building an entire ASP.NET MVC application
from start to finish. I show you how to build a simple Tasklist application.
If you have worked with Active Server Pages or ASP.NET, then you should find ASP.NET
MVC very familiar. ASP.NET MVC views are very much like the pages in an Active Server
Pages application. And, just like a traditional ASP.NET Web Forms application, ASP.NET MVC
provides you with full access to the rich set of languages and classes provided by the .NET
framework.
My hope is that this tutorial will give you a sense of how the experience of building an
ASP.NET MVC application is both similar and different than the experience of building an
Active Server Pages or ASP.NET Web Forms application.
The Tasklist Application
Because the goal is to keep things simple, we’ll be building a very simple Tasklist
application. Our simple Tasklist application will allow us to do three things:
1. List a set of task
2. Create new tasks
3. Mark a task as completed
Again, because we want to keep things simple, we’ll take advantage of the minimum
number of features of the ASP.NET MVC framework needed to build our application. For
example, we won’t be taking advantage of Test-Driven Development or HTML Helper
methods.
Preliminaries
You’ll need either Visual Studio 2008 or Visual Web Developer 2008 Express to build an
ASP.NET MVC application. You also need to download the ASP.NET MVC framework.
If you don’t own Visual Studio 2008, then you can download a 90 day trial version of Visual
Studio 2008 from this website:
http://msdn.microsoft.com/en-us/vs2008/products/cc268305.aspx
Alternatively, you can create ASP.NET MVC applications with Visual Web Developer Express
2008. If you decide to use Visual Web Developer Express then you must have Service Pack
1 installed. You can download Visual Web Developer 2008 Express with Service Pack 1 from
this website:
http://www.microsoft.com/downloads/details.aspx?FamilyId=BDB6391C-05CA-4036-9154-
6DF4F6DEBD14&displaylang=en
After you install either Visual Studio 2008 or Visual Web Developer 2008, you need to install
the ASP.NET MVC framework. You can download the ASP.NET MVC framework from the
following website:
http://www.asp.net/mvc/
Creating an ASP.NET MVC Web Application
Project
Let’s start by creating a new ASP.NET MVC Web Application project in Visual Studio 2008.
Select the menu option File, New Project and you will see the New Project dialog box in
Figure 1. Select your favorite programming language (Visual Basic or Visual C#) and select
the ASP.NET MVC Web Application project. Give your project the name TaskList and click
the OK button.
Figure 1 – The New Project dialog box
Whenever you create a new MVC Web Application project, Visual Studio prompts you to
create a separate unit test project. The dialog in Figure 2 appears. Because we won’t be
creating tests in this tutorial because of time constraints (and, yes, we should feel a little
guilty about this) select the No option and click the OK button.
Figure 2 – The Create Unit Test Project dialog
An ASP.NET MVC application has a standard set of folders: a Models, Views, and Controllers
folder. You can see this standard set of folders in the Solution Explorer window. We’ll need
to add files to the Models, Views, and Controllers folders to build our TaskList application.
When you create a new MVC application by using Visual Studio, you get a sample
application. Because we want to start from scratch, we need to delete the content for this
sample application. You need to delete the following file and the following folder:
 ControllersHomeController.cs
 ViewsHome
Creating the Controller
Typically, when building an ASP.NET MVC application, you’ll start by building a controller.
Each browser request made against an ASP.NET MVC application is handled by a controller.
A controller contains the application logic that is responsible for responding to a request.
Add a new controller to your Visual Studio project by right-clicking the Controllers folder and
selecting the menu item Add, New Item. Select the MVC Controller Class template.
Name your new controller HomeController.cs and click the Add button.
For our TaskList application, we’ll modify the HomeController class so that it contains the
code in Listing 1. The modified controller contains four functions named Index(), Create(),
CreateNew(), and Complete(). Each function corresponds to a controller action.
Listing 1 – HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TaskList.Models;
namespace TaskList.Controllers
{
public class HomeController : Controller
{
// Display a list of tasks
public ActionResult Index()
{
return View();
}
// Display a form for creating a new task
public ActionResult Create()
{
return View();
}
// Add a new task to the database
public ActionResult CreateNew()
{
return RedirectToAction("Index");
}
// Mark a task as complete
public ActionResult Complete()
{
// database logic
return RedirectToAction("Index");
}
}
}
Here’s the intention behind each of these controller actions:
 Index() – Called when you want to display the list of tasks.
 Create() – Called when you want to display the form for adding a new task.
 CreateNew() – Called when the form for adding a new task is submitted. This
controller action actually adds the new task to the database.
 Complete() – Called when a new task is marked as completed.
We’ll need to add additional logic to our controller actions to get them to work as intended.
Any public function contained in a controller class is exposed as a controller action. Be
careful about this. A controller action is exposed to the world. Anyone can call a controller
action by typing the right URL into the address bar of their web browser. So, don’t
accidently create a public function in a controller when you don’t want the function to be
called.
Notice that controller actions return an ActionResult. An ActionResult represents what the
action will do. The first two controller actions, Index() and Create(), return an MVC view.
The third and fourth action results redirect the user to another controller action.
Here’s how these controller actions work. When you request the Create() controller action,
a view containing a form for creating a new task is returned. When you submit this form,
the CreateNew() controller action is called. The CreateNew() controller action adds the new
task to the database and redirects the user to the Index() controller action. The Index()
controller action returns a view that displays the entire list of tasks. Finally, if you mark a
task as completed, the Complete() controller action is called and the database is updated.
The Complete() action redirects the user back to the Index() action and the updated list of
tasks is displayed.
Creating the Views
A view contains the HTML markup and content that is sent to the browser. A view is the
closest thing to a page in an ASP.NET MVC application. You create a view by creating a file
with the extension .aspx.
You must place a view in the right location. If you are creating a view for the Index() action
method of the HomeController, then you must place the view in a folder with the following
path:
ViewsHomeIndex.aspx
If you are creating a view for the Price() action method of the ProductController, then the
view must be placed in the following folder:
ViewsProductPrice.aspx
By default, a view should have the same name as the controller action to which it
corresponds. The view also must be placed in a folder that corresponds to its controller’s
name.
You create a view by right-clicking a subfolder in the Views folder and selecting the menu
option Add, New Item. Select the MVC View Page template to add a new view. We need to
create the following two views at the following paths:
ViewsHomeIndex.aspx
ViewsHomeCreate.aspx
After you create these two views, your Solution Explorer window should contain the files
illustrated in Figure 3.
Figure 3 – The Index.aspx and Create.aspx Views
A view can contain HTML content and scripts. The Index.aspx view will be used to display
the list of all tasks. To indicate the purpose of the view, add the content in Listing 2 to the
Index.aspx view.
Listing 2 – Index.aspx
<%@ Page Language="C#" AutoEventWireup="false"
CodeBehind="Index.aspx.cs" Inherits="TaskList.Views.Home.Index"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<div>
<h1>My Tasks</h1>
... displaying all tasks
<a href="/Home/Create">Add new Task</a>
</div>
</body>
</html>
The Index.aspx view currently does not display any tasks – it just claims that it will. We
will add the script to display the list of tasks to the Index.aspx page later in this tutorial.
Notice that the Index.aspx view includes a link labeled Add new Task. This link points to
the path /Home/Create. When you click this link, the Create() action of the
HomeController class is invoked. The Create() method returns the Create view.
The Create.aspx view contains a form for creating a new task. The contents of this view
are contained in Listing 3.
Listing 3 – Create.aspx
<%@ Page Language="C#" AutoEventWireup="false"
CodeBehind="Create.aspx.cs" Inherits="TaskList.Views.Home.Create"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<div>
<h1>Add New Task</h1>
<form method="post" action="/Home/CreateNew">
<label for="description">Task:</label>
<input type="text" name="description" />
<br />
<input type="submit" value="Add Task" />
</form>
</div>
</body>
</html>
Notice that the form contained in Listing 3 posts to the following URL:
/Home/CreateNew.aspx
This URL corresponds to the CreateNew() action on the HomeController controller. The
form data representing the new task will be posted to this action.
Creating the Database
The next step is to create the database that will contain our tasks. You can create the
database by right-clicking the App_Data folder and selecting the menu option Add, New
Item. Select the SQL Server Database template item, name the database TaskListDB.mdf,
and click the Add button.
Next, we need to add a table to our database that contains the tasks. Double-click
TaskListDB.mdf in the Solution Explorer window to open the Server Explorer window.
Right-click the Tables folder and select the Add New Table menu item. Selecting this menu
item opens the database table designer. Create the following database columns:
Column Name Data Type Allow Nulls
Id Int False
Task Nvarchar(300) False
IsCompleted Bit False
EntryDate DateTime False
The first column, the Id column, has two special properties. First, you need to mark the Id
column as the primary key column. After selecting the Id column, click the Set Primary
Key button (it is the icon that looks like a key). Second, you need to mark the Id column as
an Identity column. In the Column Properties window, scroll down to the Identity
Specification section and expand it. Change the Is Identity property to the value Yes.
When you are finished, the table should look like Figure 4.
Figure 4 – The Tasks table
The final step is to save the new table. Click the Save button (the icon of the floppy) and
give the new table the name Tasks.
Creating the Model
An MVC model contains the bulk of your application and database access logic. Normally,
you place the majority of the classes contained in your MVC application in the Models folder.
All of your application logic that is not contained in a view or a controller gets shoved into
the Models folder.
In this tutorial, we will use LINQ to SQL to communicate with the database that we created
in the previous section. Personally, I like LINQ to SQL. However, there is no requirement
that you use LINQ to SQL with an ASP.NET MVC application. If you prefer, you could use
another technology such as NHibernate or the Entity Framework to communicate with a
database.
To use LINQ to SQL, we must first create our LINQ to SQL classes in the Models folder.
Right-click the Models folder, select the Add, New Item menu item, and select the LINQ
to SQL Classes template item. Name your new LINQ to SQL classes TaskList.dbml and click
the Add button. After you complete this step, the Object Relational Designer will appear.
We need to create a single LINQ to SQL entity class that represents our Tasks database
table. Drag the Tasks database table from the Solution Explorer window onto the Object
Relational Designer. Performing this last action creates a new LINQ to SQL entity class
named Task (see Figure 5). Click the Save button (the icon of the floppy) to save the new
entity.
Figure 5 – The Task Entity
Adding Database Logic to the Controller
Methods
Now that we have a database, we can modify our controller actions so that we can store
and retrieve tasks from the database. The modified HomeController is contained in Listing
4.
Listing 4 – HomeController.vb
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TaskList.Models;
namespace TaskList.Controllers
{
public class HomeController : Controller
{
private TaskListDataContext db = new TaskListDataContext();
// Display a list of tasks
public ActionResult Index()
{
var tasks = from t in db.Tasks
orderby t.EntryDate
descending select t;
return View(tasks.ToList());
}
// Display a form for creating a new task
public ActionResult Create()
{
return View();
}
// Add a new task to the database
public ActionResult CreateNew(string description)
{
// Add the new task to database
Task newTask = new Task();
newTask.Description = description;
newTask.IsCompleted = false;
newTask.EntryDate = DateTime.Now;
db.Tasks.InsertOnSubmit(newTask);
db.SubmitChanges();
return RedirectToAction("Index");
}
// Mark a task as complete
public ActionResult Complete(int Id)
{
// database logic
var tasks = from t in db.Tasks where t.Id == Id select
t;
foreach (Task match in tasks)
match.IsCompleted = true;
db.SubmitChanges();
return RedirectToAction("Index");
}
}
}
Notice that the HomeController class in Listing 4 contains a class-level private field named
db. The db field is an instance of the TaskListDataContext class. The HomeController
class uses the db field to represent the TaskListDB database.
The Index() controller action has been modified to retrieve all of the records from the
Tasks database table. The tasks are passed to the Index view.
The CreateNew() method has been modified to create a new task in the Tasks database
table. Notice that the CreateNew() method has been modified to accept a String parameter
named description. This parameter represents the description text form field passed from
the Create view. The ASP.NET MVC framework passes form fields as parameters to a
controller action automatically.
Finally, the Complete() method has been modified to change the value of the IsComplete
column in the Tasks database table. When you mark a task as complete, the Id of the task
is passed to the Complete() action and the database is updated.
Modifying the Index View
There is one final thing that we must do in order to complete our Tasklist application. We
must modify the Index view so that it displays a list of all of the tasks and it allows us to
mark a task as complete. The modified Index view is contained in Listing 5.
Listing 5 – Index.aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="Index.aspx.cs" Inherits="TaskList.Views.Home.Index"
%>
<%@ Import Namespace="TaskList.Models" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Index</title>
</head>
<body>
<div>
<h1>My Tasks</h1>
<ul>
<% foreach (Task task in (IEnumerable)ViewData.Model) { %>
<li>
<% if (task.IsCompleted) {%>
<del>
<%= task.EntryDate.ToShortDateString() %>
-- <%=task.Description%>
</del>
<% } else {%>
<a href="/Home/Complete/<%= task.Id.ToString()
%>">Complete</a>
<%= task.EntryDate.ToShortDateString() %>
-- <%=task.Description%>
<% }%>
</li>
<% } %>
</ul>
<br /><br />
<a href="/Home/Create">Add new Task</a>
</div>
</body>
</html>
The Index view in Listing 5 contains a C# foreach loop that iterates through all of the tasks.
The tasks are represented with the ViewData.Model property. In general, you use ViewData
to pass data from a controller action to a view.
Within the loop, a conditional is used to check whether a task has been completed. A
completed task is shown with a line through it (struck out). The HTML <del> tag is used to
create the line through the completed tasks. If a task has not been completed, a link labeled
Complete is displayed next to the task. The link is constructed with the following script:
<a href="/Home/Complete/<%= task.Id.ToString() %>">Complete</a>
Notice that the Id of the task is included in the URL represented by the link. The task Id is
passed to the Complete() action of the HomeController class when you click a link. In this
way, the right database record is updated when you click the Complete link.
The final version of the Index view displays the page contained in Figure 6.
Figure 6 – The Index View
Summary
The purpose of this tutorial was to give you a sense of the experience of building an
ASP.NET MVC application. I hope that you discovered that building an ASP.NET MVC web
application is very similar to the experience of building an Active Server Pages or ASP.NET
application.
In this tutorial, we examined only the most basic features of the ASP.NET MVC framework.
In future tutorials, we dive deeper into topics such as controllers, controller actions, views,
view data, and HTML helpers.
Ad

More Related Content

What's hot (20)

Tutorial 1
Tutorial 1Tutorial 1
Tutorial 1
Aravindharamanan S
 
Part 1 implementing a simple_web_service
Part 1 implementing a simple_web_servicePart 1 implementing a simple_web_service
Part 1 implementing a simple_web_service
krishmdkk
 
03 asp.net session04
03 asp.net session0403 asp.net session04
03 asp.net session04
Vivek Singh Chandel
 
Chapter 09
Chapter 09Chapter 09
Chapter 09
Terry Yoast
 
IMPACT/myGrid Hackathon - Introduction to Taverna
IMPACT/myGrid Hackathon - Introduction to TavernaIMPACT/myGrid Hackathon - Introduction to Taverna
IMPACT/myGrid Hackathon - Introduction to Taverna
IMPACT Centre of Competence
 
03 asp.net session04
03 asp.net session0403 asp.net session04
03 asp.net session04
Mani Chaubey
 
Point and Click App Building Workshop
Point and Click App Building WorkshopPoint and Click App Building Workshop
Point and Click App Building Workshop
Salesforce Developers
 
Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4
Rich Helton
 
Murach : HOW to work with controllers and routing
Murach : HOW to work with controllers and routingMurach : HOW to work with controllers and routing
Murach : HOW to work with controllers and routing
MahmoudOHassouna
 
AngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPIAngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPI
Eric Wise
 
Inversion of control using dependency injection in Web APIs using Unity Conta...
Inversion of control using dependency injection in Web APIs using Unity Conta...Inversion of control using dependency injection in Web APIs using Unity Conta...
Inversion of control using dependency injection in Web APIs using Unity Conta...
Akhil Mittal
 
Murach : How to work with session state and cookies
Murach : How to work with session state and cookiesMurach : How to work with session state and cookies
Murach : How to work with session state and cookies
MahmoudOHassouna
 
Laravel mail example how to send an email using markdown template in laravel 8
Laravel mail example how to send an email using markdown template in laravel 8Laravel mail example how to send an email using markdown template in laravel 8
Laravel mail example how to send an email using markdown template in laravel 8
Katy Slemon
 
Les24
Les24Les24
Les24
Sudharsan S
 
Asp 2-createaspnetmvc
Asp 2-createaspnetmvcAsp 2-createaspnetmvc
Asp 2-createaspnetmvc
Fajar Baskoro
 
How to develop a gateway service using code based implementation
How to develop a gateway service using code based implementationHow to develop a gateway service using code based implementation
How to develop a gateway service using code based implementation
nitin2517
 
Leture5 exercise onactivities
Leture5 exercise onactivitiesLeture5 exercise onactivities
Leture5 exercise onactivities
maamir farooq
 
Katalon Studio - GUI Overview
Katalon Studio - GUI OverviewKatalon Studio - GUI Overview
Katalon Studio - GUI Overview
Katalon Studio
 
React native app with type script tutorial
React native app with type script tutorialReact native app with type script tutorial
React native app with type script tutorial
Katy Slemon
 
Adding User Management to Node.js
Adding User Management to Node.jsAdding User Management to Node.js
Adding User Management to Node.js
Dev_Events
 
Part 1 implementing a simple_web_service
Part 1 implementing a simple_web_servicePart 1 implementing a simple_web_service
Part 1 implementing a simple_web_service
krishmdkk
 
IMPACT/myGrid Hackathon - Introduction to Taverna
IMPACT/myGrid Hackathon - Introduction to TavernaIMPACT/myGrid Hackathon - Introduction to Taverna
IMPACT/myGrid Hackathon - Introduction to Taverna
IMPACT Centre of Competence
 
03 asp.net session04
03 asp.net session0403 asp.net session04
03 asp.net session04
Mani Chaubey
 
Point and Click App Building Workshop
Point and Click App Building WorkshopPoint and Click App Building Workshop
Point and Click App Building Workshop
Salesforce Developers
 
Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4
Rich Helton
 
Murach : HOW to work with controllers and routing
Murach : HOW to work with controllers and routingMurach : HOW to work with controllers and routing
Murach : HOW to work with controllers and routing
MahmoudOHassouna
 
AngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPIAngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPI
Eric Wise
 
Inversion of control using dependency injection in Web APIs using Unity Conta...
Inversion of control using dependency injection in Web APIs using Unity Conta...Inversion of control using dependency injection in Web APIs using Unity Conta...
Inversion of control using dependency injection in Web APIs using Unity Conta...
Akhil Mittal
 
Murach : How to work with session state and cookies
Murach : How to work with session state and cookiesMurach : How to work with session state and cookies
Murach : How to work with session state and cookies
MahmoudOHassouna
 
Laravel mail example how to send an email using markdown template in laravel 8
Laravel mail example how to send an email using markdown template in laravel 8Laravel mail example how to send an email using markdown template in laravel 8
Laravel mail example how to send an email using markdown template in laravel 8
Katy Slemon
 
Asp 2-createaspnetmvc
Asp 2-createaspnetmvcAsp 2-createaspnetmvc
Asp 2-createaspnetmvc
Fajar Baskoro
 
How to develop a gateway service using code based implementation
How to develop a gateway service using code based implementationHow to develop a gateway service using code based implementation
How to develop a gateway service using code based implementation
nitin2517
 
Leture5 exercise onactivities
Leture5 exercise onactivitiesLeture5 exercise onactivities
Leture5 exercise onactivities
maamir farooq
 
Katalon Studio - GUI Overview
Katalon Studio - GUI OverviewKatalon Studio - GUI Overview
Katalon Studio - GUI Overview
Katalon Studio
 
React native app with type script tutorial
React native app with type script tutorialReact native app with type script tutorial
React native app with type script tutorial
Katy Slemon
 
Adding User Management to Node.js
Adding User Management to Node.jsAdding User Management to Node.js
Adding User Management to Node.js
Dev_Events
 

Similar to Aspnet mvc tutorial_01_cs (20)

Adding a view
Adding a viewAdding a view
Adding a view
Nhan Do
 
Scaffolding
ScaffoldingScaffolding
Scaffolding
DrMohamed Oaf
 
Model view controller (mvc)
Model view controller (mvc)Model view controller (mvc)
Model view controller (mvc)
M Ahsan Khan
 
ASP.NET Identity
ASP.NET IdentityASP.NET Identity
ASP.NET Identity
Suzanne Simmons
 
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) kerenTutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
Sony Suci
 
Mvc summary
Mvc summaryMvc summary
Mvc summary
Muhammad Younis
 
Building richwebapplicationsusingasp
Building richwebapplicationsusingaspBuilding richwebapplicationsusingasp
Building richwebapplicationsusingasp
Giovanni Javier Jimenez Cadena
 
AspMVC4 start101
AspMVC4 start101AspMVC4 start101
AspMVC4 start101
Rich Helton
 
Model View Presenter (MVP) In Aspnet
Model View Presenter (MVP) In AspnetModel View Presenter (MVP) In Aspnet
Model View Presenter (MVP) In Aspnet
rainynovember12
 
Introduction-to-ASPNET-Core ASP.NET.pptx
Introduction-to-ASPNET-Core ASP.NET.pptxIntroduction-to-ASPNET-Core ASP.NET.pptx
Introduction-to-ASPNET-Core ASP.NET.pptx
MAHERMOHAMED27
 
Task scheduling in laravel 8 tutorial
Task scheduling in laravel 8 tutorialTask scheduling in laravel 8 tutorial
Task scheduling in laravel 8 tutorial
Katy Slemon
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
vchircu
 
Steps how to create active x using visual studio 2008
Steps how to create active x using visual studio 2008Steps how to create active x using visual studio 2008
Steps how to create active x using visual studio 2008
Yudep Apoi
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
Aravindharamanan S
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
Aravindharamanan S
 
Mvc acchitecture
Mvc acchitectureMvc acchitecture
Mvc acchitecture
laxmi.katkar
 
Asp.Net MVC Intro
Asp.Net MVC IntroAsp.Net MVC Intro
Asp.Net MVC Intro
Stefano Paluello
 
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5  Building Your First Web Application (A Beginner S GuideASP.NET MVC 5  Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
Alicia Buske
 
ASP.NET MVC3 RAD
ASP.NET MVC3 RADASP.NET MVC3 RAD
ASP.NET MVC3 RAD
Mădălin Ștefîrcă
 
ASP.NET MVC Introduction
ASP.NET MVC IntroductionASP.NET MVC Introduction
ASP.NET MVC Introduction
Sumit Chhabra
 
Adding a view
Adding a viewAdding a view
Adding a view
Nhan Do
 
Model view controller (mvc)
Model view controller (mvc)Model view controller (mvc)
Model view controller (mvc)
M Ahsan Khan
 
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) kerenTutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
Sony Suci
 
AspMVC4 start101
AspMVC4 start101AspMVC4 start101
AspMVC4 start101
Rich Helton
 
Model View Presenter (MVP) In Aspnet
Model View Presenter (MVP) In AspnetModel View Presenter (MVP) In Aspnet
Model View Presenter (MVP) In Aspnet
rainynovember12
 
Introduction-to-ASPNET-Core ASP.NET.pptx
Introduction-to-ASPNET-Core ASP.NET.pptxIntroduction-to-ASPNET-Core ASP.NET.pptx
Introduction-to-ASPNET-Core ASP.NET.pptx
MAHERMOHAMED27
 
Task scheduling in laravel 8 tutorial
Task scheduling in laravel 8 tutorialTask scheduling in laravel 8 tutorial
Task scheduling in laravel 8 tutorial
Katy Slemon
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
vchircu
 
Steps how to create active x using visual studio 2008
Steps how to create active x using visual studio 2008Steps how to create active x using visual studio 2008
Steps how to create active x using visual studio 2008
Yudep Apoi
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
Aravindharamanan S
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
Aravindharamanan S
 
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5  Building Your First Web Application (A Beginner S GuideASP.NET MVC 5  Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
Alicia Buske
 
ASP.NET MVC Introduction
ASP.NET MVC IntroductionASP.NET MVC Introduction
ASP.NET MVC Introduction
Sumit Chhabra
 
Ad

More from Alfa Gama Omega (8)

B1 manual vacio
B1 manual vacioB1 manual vacio
B1 manual vacio
Alfa Gama Omega
 
Calderas viessman oil gas-boilers-and-hot-water-boilers
Calderas viessman oil gas-boilers-and-hot-water-boilersCalderas viessman oil gas-boilers-and-hot-water-boilers
Calderas viessman oil gas-boilers-and-hot-water-boilers
Alfa Gama Omega
 
B1 manual vacio
B1 manual vacioB1 manual vacio
B1 manual vacio
Alfa Gama Omega
 
Aermec guida idronica_es
Aermec guida idronica_esAermec guida idronica_es
Aermec guida idronica_es
Alfa Gama Omega
 
Aermec guida idronica_es
Aermec guida idronica_esAermec guida idronica_es
Aermec guida idronica_es
Alfa Gama Omega
 
Mosfet irfz44
Mosfet irfz44Mosfet irfz44
Mosfet irfz44
Alfa Gama Omega
 
Mosfet irfz44 n 1 philips semiconductors
Mosfet irfz44 n 1 philips semiconductorsMosfet irfz44 n 1 philips semiconductors
Mosfet irfz44 n 1 philips semiconductors
Alfa Gama Omega
 
Diapositivas api 650
Diapositivas api 650Diapositivas api 650
Diapositivas api 650
Alfa Gama Omega
 
Calderas viessman oil gas-boilers-and-hot-water-boilers
Calderas viessman oil gas-boilers-and-hot-water-boilersCalderas viessman oil gas-boilers-and-hot-water-boilers
Calderas viessman oil gas-boilers-and-hot-water-boilers
Alfa Gama Omega
 
Aermec guida idronica_es
Aermec guida idronica_esAermec guida idronica_es
Aermec guida idronica_es
Alfa Gama Omega
 
Aermec guida idronica_es
Aermec guida idronica_esAermec guida idronica_es
Aermec guida idronica_es
Alfa Gama Omega
 
Mosfet irfz44 n 1 philips semiconductors
Mosfet irfz44 n 1 philips semiconductorsMosfet irfz44 n 1 philips semiconductors
Mosfet irfz44 n 1 philips semiconductors
Alfa Gama Omega
 
Ad

Recently uploaded (20)

Dust Suppressants: A Sustainable Approach to Dust Pollution Control
Dust Suppressants: A Sustainable Approach to Dust Pollution ControlDust Suppressants: A Sustainable Approach to Dust Pollution Control
Dust Suppressants: A Sustainable Approach to Dust Pollution Control
Janapriya Roy
 
BCS401 ADA Second IA Test Question Bank.pdf
BCS401 ADA Second IA Test Question Bank.pdfBCS401 ADA Second IA Test Question Bank.pdf
BCS401 ADA Second IA Test Question Bank.pdf
VENKATESHBHAT25
 
How to Make Material Space Qu___ (1).pptx
How to Make Material Space Qu___ (1).pptxHow to Make Material Space Qu___ (1).pptx
How to Make Material Space Qu___ (1).pptx
engaash9
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
Basic Principles for Electronics Students
Basic Principles for Electronics StudentsBasic Principles for Electronics Students
Basic Principles for Electronics Students
cbdbizdev04
 
Elevate Your Workflow
Elevate Your WorkflowElevate Your Workflow
Elevate Your Workflow
NickHuld
 
Lecture 13 (Air and Noise Pollution and their Control) (1).pptx
Lecture 13 (Air and Noise Pollution and their Control) (1).pptxLecture 13 (Air and Noise Pollution and their Control) (1).pptx
Lecture 13 (Air and Noise Pollution and their Control) (1).pptx
huzaifabilalshams
 
Gas Power Plant for Power Generation System
Gas Power Plant for Power Generation SystemGas Power Plant for Power Generation System
Gas Power Plant for Power Generation System
JourneyWithMe1
 
Taking AI Welfare Seriously, In this report, we argue that there is a realist...
Taking AI Welfare Seriously, In this report, we argue that there is a realist...Taking AI Welfare Seriously, In this report, we argue that there is a realist...
Taking AI Welfare Seriously, In this report, we argue that there is a realist...
MiguelMarques372250
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
BTech_CSE_LPU_Presentation.pptx.........
BTech_CSE_LPU_Presentation.pptx.........BTech_CSE_LPU_Presentation.pptx.........
BTech_CSE_LPU_Presentation.pptx.........
jinny kaur
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
Crack the Domain with Event Storming By Vivek
Crack the Domain with Event Storming By VivekCrack the Domain with Event Storming By Vivek
Crack the Domain with Event Storming By Vivek
Vivek Srivastava
 
Dust Suppressants: A Sustainable Approach to Dust Pollution Control
Dust Suppressants: A Sustainable Approach to Dust Pollution ControlDust Suppressants: A Sustainable Approach to Dust Pollution Control
Dust Suppressants: A Sustainable Approach to Dust Pollution Control
Janapriya Roy
 
BCS401 ADA Second IA Test Question Bank.pdf
BCS401 ADA Second IA Test Question Bank.pdfBCS401 ADA Second IA Test Question Bank.pdf
BCS401 ADA Second IA Test Question Bank.pdf
VENKATESHBHAT25
 
How to Make Material Space Qu___ (1).pptx
How to Make Material Space Qu___ (1).pptxHow to Make Material Space Qu___ (1).pptx
How to Make Material Space Qu___ (1).pptx
engaash9
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
Basic Principles for Electronics Students
Basic Principles for Electronics StudentsBasic Principles for Electronics Students
Basic Principles for Electronics Students
cbdbizdev04
 
Elevate Your Workflow
Elevate Your WorkflowElevate Your Workflow
Elevate Your Workflow
NickHuld
 
Lecture 13 (Air and Noise Pollution and their Control) (1).pptx
Lecture 13 (Air and Noise Pollution and their Control) (1).pptxLecture 13 (Air and Noise Pollution and their Control) (1).pptx
Lecture 13 (Air and Noise Pollution and their Control) (1).pptx
huzaifabilalshams
 
Gas Power Plant for Power Generation System
Gas Power Plant for Power Generation SystemGas Power Plant for Power Generation System
Gas Power Plant for Power Generation System
JourneyWithMe1
 
Taking AI Welfare Seriously, In this report, we argue that there is a realist...
Taking AI Welfare Seriously, In this report, we argue that there is a realist...Taking AI Welfare Seriously, In this report, we argue that there is a realist...
Taking AI Welfare Seriously, In this report, we argue that there is a realist...
MiguelMarques372250
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
BTech_CSE_LPU_Presentation.pptx.........
BTech_CSE_LPU_Presentation.pptx.........BTech_CSE_LPU_Presentation.pptx.........
BTech_CSE_LPU_Presentation.pptx.........
jinny kaur
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
Crack the Domain with Event Storming By Vivek
Crack the Domain with Event Storming By VivekCrack the Domain with Event Storming By Vivek
Crack the Domain with Event Storming By Vivek
Vivek Srivastava
 

Aspnet mvc tutorial_01_cs

  • 1. MVC :: Creating a Tasklist Application with ASP.NET MVC The purpose of this tutorial is to give you a sense of “what it is like” to build an ASP.NET MVC application. In this tutorial, I blast through building an entire ASP.NET MVC application from start to finish. I show you how to build a simple Tasklist application. If you have worked with Active Server Pages or ASP.NET, then you should find ASP.NET MVC very familiar. ASP.NET MVC views are very much like the pages in an Active Server Pages application. And, just like a traditional ASP.NET Web Forms application, ASP.NET MVC provides you with full access to the rich set of languages and classes provided by the .NET framework. My hope is that this tutorial will give you a sense of how the experience of building an ASP.NET MVC application is both similar and different than the experience of building an Active Server Pages or ASP.NET Web Forms application. The Tasklist Application Because the goal is to keep things simple, we’ll be building a very simple Tasklist application. Our simple Tasklist application will allow us to do three things: 1. List a set of task 2. Create new tasks 3. Mark a task as completed Again, because we want to keep things simple, we’ll take advantage of the minimum number of features of the ASP.NET MVC framework needed to build our application. For example, we won’t be taking advantage of Test-Driven Development or HTML Helper methods. Preliminaries You’ll need either Visual Studio 2008 or Visual Web Developer 2008 Express to build an ASP.NET MVC application. You also need to download the ASP.NET MVC framework. If you don’t own Visual Studio 2008, then you can download a 90 day trial version of Visual Studio 2008 from this website: http://msdn.microsoft.com/en-us/vs2008/products/cc268305.aspx Alternatively, you can create ASP.NET MVC applications with Visual Web Developer Express 2008. If you decide to use Visual Web Developer Express then you must have Service Pack 1 installed. You can download Visual Web Developer 2008 Express with Service Pack 1 from this website: http://www.microsoft.com/downloads/details.aspx?FamilyId=BDB6391C-05CA-4036-9154- 6DF4F6DEBD14&displaylang=en
  • 2. After you install either Visual Studio 2008 or Visual Web Developer 2008, you need to install the ASP.NET MVC framework. You can download the ASP.NET MVC framework from the following website: http://www.asp.net/mvc/ Creating an ASP.NET MVC Web Application Project Let’s start by creating a new ASP.NET MVC Web Application project in Visual Studio 2008. Select the menu option File, New Project and you will see the New Project dialog box in Figure 1. Select your favorite programming language (Visual Basic or Visual C#) and select the ASP.NET MVC Web Application project. Give your project the name TaskList and click the OK button. Figure 1 – The New Project dialog box Whenever you create a new MVC Web Application project, Visual Studio prompts you to create a separate unit test project. The dialog in Figure 2 appears. Because we won’t be creating tests in this tutorial because of time constraints (and, yes, we should feel a little guilty about this) select the No option and click the OK button.
  • 3. Figure 2 – The Create Unit Test Project dialog An ASP.NET MVC application has a standard set of folders: a Models, Views, and Controllers folder. You can see this standard set of folders in the Solution Explorer window. We’ll need to add files to the Models, Views, and Controllers folders to build our TaskList application. When you create a new MVC application by using Visual Studio, you get a sample application. Because we want to start from scratch, we need to delete the content for this sample application. You need to delete the following file and the following folder:  ControllersHomeController.cs  ViewsHome Creating the Controller Typically, when building an ASP.NET MVC application, you’ll start by building a controller. Each browser request made against an ASP.NET MVC application is handled by a controller. A controller contains the application logic that is responsible for responding to a request. Add a new controller to your Visual Studio project by right-clicking the Controllers folder and selecting the menu item Add, New Item. Select the MVC Controller Class template. Name your new controller HomeController.cs and click the Add button. For our TaskList application, we’ll modify the HomeController class so that it contains the code in Listing 1. The modified controller contains four functions named Index(), Create(), CreateNew(), and Complete(). Each function corresponds to a controller action. Listing 1 – HomeController.cs using System;
  • 4. using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using TaskList.Models; namespace TaskList.Controllers { public class HomeController : Controller { // Display a list of tasks public ActionResult Index() { return View(); } // Display a form for creating a new task public ActionResult Create() { return View(); } // Add a new task to the database public ActionResult CreateNew() { return RedirectToAction("Index"); } // Mark a task as complete public ActionResult Complete() { // database logic return RedirectToAction("Index"); }
  • 5. } } Here’s the intention behind each of these controller actions:  Index() – Called when you want to display the list of tasks.  Create() – Called when you want to display the form for adding a new task.  CreateNew() – Called when the form for adding a new task is submitted. This controller action actually adds the new task to the database.  Complete() – Called when a new task is marked as completed. We’ll need to add additional logic to our controller actions to get them to work as intended. Any public function contained in a controller class is exposed as a controller action. Be careful about this. A controller action is exposed to the world. Anyone can call a controller action by typing the right URL into the address bar of their web browser. So, don’t accidently create a public function in a controller when you don’t want the function to be called. Notice that controller actions return an ActionResult. An ActionResult represents what the action will do. The first two controller actions, Index() and Create(), return an MVC view. The third and fourth action results redirect the user to another controller action. Here’s how these controller actions work. When you request the Create() controller action, a view containing a form for creating a new task is returned. When you submit this form, the CreateNew() controller action is called. The CreateNew() controller action adds the new task to the database and redirects the user to the Index() controller action. The Index() controller action returns a view that displays the entire list of tasks. Finally, if you mark a task as completed, the Complete() controller action is called and the database is updated. The Complete() action redirects the user back to the Index() action and the updated list of tasks is displayed. Creating the Views A view contains the HTML markup and content that is sent to the browser. A view is the closest thing to a page in an ASP.NET MVC application. You create a view by creating a file with the extension .aspx. You must place a view in the right location. If you are creating a view for the Index() action method of the HomeController, then you must place the view in a folder with the following path: ViewsHomeIndex.aspx If you are creating a view for the Price() action method of the ProductController, then the view must be placed in the following folder: ViewsProductPrice.aspx
  • 6. By default, a view should have the same name as the controller action to which it corresponds. The view also must be placed in a folder that corresponds to its controller’s name. You create a view by right-clicking a subfolder in the Views folder and selecting the menu option Add, New Item. Select the MVC View Page template to add a new view. We need to create the following two views at the following paths: ViewsHomeIndex.aspx ViewsHomeCreate.aspx After you create these two views, your Solution Explorer window should contain the files illustrated in Figure 3. Figure 3 – The Index.aspx and Create.aspx Views A view can contain HTML content and scripts. The Index.aspx view will be used to display the list of all tasks. To indicate the purpose of the view, add the content in Listing 2 to the Index.aspx view. Listing 2 – Index.aspx <%@ Page Language="C#" AutoEventWireup="false" CodeBehind="Index.aspx.cs" Inherits="TaskList.Views.Home.Index" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  • 7. <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title></title> </head> <body> <div> <h1>My Tasks</h1> ... displaying all tasks <a href="/Home/Create">Add new Task</a> </div> </body> </html> The Index.aspx view currently does not display any tasks – it just claims that it will. We will add the script to display the list of tasks to the Index.aspx page later in this tutorial. Notice that the Index.aspx view includes a link labeled Add new Task. This link points to the path /Home/Create. When you click this link, the Create() action of the HomeController class is invoked. The Create() method returns the Create view. The Create.aspx view contains a form for creating a new task. The contents of this view are contained in Listing 3. Listing 3 – Create.aspx <%@ Page Language="C#" AutoEventWireup="false" CodeBehind="Create.aspx.cs" Inherits="TaskList.Views.Home.Create" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title></title>
  • 8. </head> <body> <div> <h1>Add New Task</h1> <form method="post" action="/Home/CreateNew"> <label for="description">Task:</label> <input type="text" name="description" /> <br /> <input type="submit" value="Add Task" /> </form> </div> </body> </html> Notice that the form contained in Listing 3 posts to the following URL: /Home/CreateNew.aspx This URL corresponds to the CreateNew() action on the HomeController controller. The form data representing the new task will be posted to this action. Creating the Database The next step is to create the database that will contain our tasks. You can create the database by right-clicking the App_Data folder and selecting the menu option Add, New Item. Select the SQL Server Database template item, name the database TaskListDB.mdf, and click the Add button. Next, we need to add a table to our database that contains the tasks. Double-click TaskListDB.mdf in the Solution Explorer window to open the Server Explorer window. Right-click the Tables folder and select the Add New Table menu item. Selecting this menu item opens the database table designer. Create the following database columns: Column Name Data Type Allow Nulls
  • 9. Id Int False Task Nvarchar(300) False IsCompleted Bit False EntryDate DateTime False The first column, the Id column, has two special properties. First, you need to mark the Id column as the primary key column. After selecting the Id column, click the Set Primary Key button (it is the icon that looks like a key). Second, you need to mark the Id column as an Identity column. In the Column Properties window, scroll down to the Identity Specification section and expand it. Change the Is Identity property to the value Yes. When you are finished, the table should look like Figure 4.
  • 10. Figure 4 – The Tasks table The final step is to save the new table. Click the Save button (the icon of the floppy) and give the new table the name Tasks. Creating the Model An MVC model contains the bulk of your application and database access logic. Normally, you place the majority of the classes contained in your MVC application in the Models folder. All of your application logic that is not contained in a view or a controller gets shoved into the Models folder. In this tutorial, we will use LINQ to SQL to communicate with the database that we created in the previous section. Personally, I like LINQ to SQL. However, there is no requirement that you use LINQ to SQL with an ASP.NET MVC application. If you prefer, you could use
  • 11. another technology such as NHibernate or the Entity Framework to communicate with a database. To use LINQ to SQL, we must first create our LINQ to SQL classes in the Models folder. Right-click the Models folder, select the Add, New Item menu item, and select the LINQ to SQL Classes template item. Name your new LINQ to SQL classes TaskList.dbml and click the Add button. After you complete this step, the Object Relational Designer will appear. We need to create a single LINQ to SQL entity class that represents our Tasks database table. Drag the Tasks database table from the Solution Explorer window onto the Object Relational Designer. Performing this last action creates a new LINQ to SQL entity class named Task (see Figure 5). Click the Save button (the icon of the floppy) to save the new entity. Figure 5 – The Task Entity Adding Database Logic to the Controller Methods Now that we have a database, we can modify our controller actions so that we can store and retrieve tasks from the database. The modified HomeController is contained in Listing 4.
  • 12. Listing 4 – HomeController.vb using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using TaskList.Models; namespace TaskList.Controllers { public class HomeController : Controller { private TaskListDataContext db = new TaskListDataContext(); // Display a list of tasks public ActionResult Index() { var tasks = from t in db.Tasks orderby t.EntryDate descending select t; return View(tasks.ToList()); } // Display a form for creating a new task public ActionResult Create() { return View(); } // Add a new task to the database public ActionResult CreateNew(string description) { // Add the new task to database
  • 13. Task newTask = new Task(); newTask.Description = description; newTask.IsCompleted = false; newTask.EntryDate = DateTime.Now; db.Tasks.InsertOnSubmit(newTask); db.SubmitChanges(); return RedirectToAction("Index"); } // Mark a task as complete public ActionResult Complete(int Id) { // database logic var tasks = from t in db.Tasks where t.Id == Id select t; foreach (Task match in tasks) match.IsCompleted = true; db.SubmitChanges(); return RedirectToAction("Index"); } } } Notice that the HomeController class in Listing 4 contains a class-level private field named db. The db field is an instance of the TaskListDataContext class. The HomeController class uses the db field to represent the TaskListDB database. The Index() controller action has been modified to retrieve all of the records from the Tasks database table. The tasks are passed to the Index view. The CreateNew() method has been modified to create a new task in the Tasks database table. Notice that the CreateNew() method has been modified to accept a String parameter named description. This parameter represents the description text form field passed from the Create view. The ASP.NET MVC framework passes form fields as parameters to a controller action automatically.
  • 14. Finally, the Complete() method has been modified to change the value of the IsComplete column in the Tasks database table. When you mark a task as complete, the Id of the task is passed to the Complete() action and the database is updated. Modifying the Index View There is one final thing that we must do in order to complete our Tasklist application. We must modify the Index view so that it displays a list of all of the tasks and it allows us to mark a task as complete. The modified Index view is contained in Listing 5. Listing 5 – Index.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="TaskList.Views.Home.Index" %> <%@ Import Namespace="TaskList.Models" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Index</title> </head> <body> <div> <h1>My Tasks</h1> <ul> <% foreach (Task task in (IEnumerable)ViewData.Model) { %> <li> <% if (task.IsCompleted) {%> <del> <%= task.EntryDate.ToShortDateString() %> -- <%=task.Description%> </del> <% } else {%> <a href="/Home/Complete/<%= task.Id.ToString() %>">Complete</a> <%= task.EntryDate.ToShortDateString() %>
  • 15. -- <%=task.Description%> <% }%> </li> <% } %> </ul> <br /><br /> <a href="/Home/Create">Add new Task</a> </div> </body> </html> The Index view in Listing 5 contains a C# foreach loop that iterates through all of the tasks. The tasks are represented with the ViewData.Model property. In general, you use ViewData to pass data from a controller action to a view. Within the loop, a conditional is used to check whether a task has been completed. A completed task is shown with a line through it (struck out). The HTML <del> tag is used to create the line through the completed tasks. If a task has not been completed, a link labeled Complete is displayed next to the task. The link is constructed with the following script: <a href="/Home/Complete/<%= task.Id.ToString() %>">Complete</a> Notice that the Id of the task is included in the URL represented by the link. The task Id is passed to the Complete() action of the HomeController class when you click a link. In this way, the right database record is updated when you click the Complete link. The final version of the Index view displays the page contained in Figure 6.
  • 16. Figure 6 – The Index View Summary The purpose of this tutorial was to give you a sense of the experience of building an ASP.NET MVC application. I hope that you discovered that building an ASP.NET MVC web application is very similar to the experience of building an Active Server Pages or ASP.NET application. In this tutorial, we examined only the most basic features of the ASP.NET MVC framework. In future tutorials, we dive deeper into topics such as controllers, controller actions, views, view data, and HTML helpers.