by November 7, 2009 0 comments



ASP.NET Model-View-Controller (MVC) breaks down Web application into three
components: Model, View, and Controller. MVC framework is defined in
‘System.Web.Mvc’ namespace and is integrated with existing ASP.NET features. One
can use both traditional ASP.NET Web Form based approach and ASP.NET MVC based
approach in building an application. Both these approaches have their sets of
pros and cons. Using ASP.NET MVC makes application building simpler, for there
is clear separation between application tasks, testability, and test driven
development. Each component of MVC is built in such a way that they can easily
be customized or replaced giving much needed flexibility to developers like
parallel application development. One more benefit of MVC based application is
ease of testability when compared with Web Form based approach of application
development, as later uses single class to both display output and respond to
user interaction. Here is a brief explanation of the three components of MVC.
Model objects are components of application that define application’s data
domain like product related data in a given application. View on the other hand
is responsible to display application’s user interface. Finally controller
handles user interaction, work with models and selects appropriate views.

Direct Hit!

Applies To: Web Developers
USP: Component based web application
development
Primary Link:
www.asp.net/mvc
Search Engine Keywords: ASP.NET MVC

Implementation
In this sample implementation, we are going to create a sample website using
MVC framework that will list products along with price and date of issue in
which their review was carried. Besides this, this web site would also allow
user to add new products to existing product list plus edit records. Here we are
using Visual Studio 2010 Beta 1 with C# as programming language. You can also
use Visual Studio 2008 with .NET 3.5 SP1. For database connectivity, we are
using SQL 2008 Express database. Before using ASP.NET MVC, you need to install
this framework along with the toolkit. You can download ASP.NET MVC framework
for Visual Studio 2010 Beta 1 from http://tinyurl. com/lhwzcu. Simply install
the downloaded ‘AspNetMVC1.1_VS2010.exe’ file which in turn would add new MVC
project template to your Visual Studio. Now to create MVC based website, open
Visual Studio and create new project by clicking ‘File>New>Project’. From the
‘New Project’ window, select ‘ASP.NET MVC Web Application’ project template
under ‘Visual C#>Web’ and give it an appropriate name (‘MvcApplication1’). This
would prompt you to create test project for unit testing. Select Yes or No
depending upon whether you need to unit test your web application or not.

The output of created MVC web application. Click on ‘Create
New’ to add new record and click on ‘Edit’ to edit record.

 

If you make data type mismatch mistakewhile adding new
record, it is highlighted as shown above.

Before building web application, we start with creating data on which our
application will work. For this, right click ‘App_Data’ in ‘Solution Explorer’
and click on ‘Add>New Item’. Select ‘SQL Server Database’ template under ‘Data’
category in given window and name your database (‘Database1’). Now that we have
database, we need to add table to it and then populate that table with
appropriate data. For this, right click on ‘Table’ folder in Server Explorer
(double click on the created database in Solution Explorer) and select ‘Add New
Table’. Add columns to your table. For this application, we added four columns:
ID that takes integer data types defined as primary key and identity column,
ProductName, ProductPrice, and issue date defined as date data type. To make ID
as primary key, right click it and select ‘Set Primary Key’ and to make it
identity column, change the value of ‘Is Identity’ property to ‘Yes’. To
populate this table with data, right click on created table in the Server
Explorer and select ‘Show Table Data’.

To create model, right click on ‘Models’ folder in Solution
Explorer and click on ‘Add>New Item’.

Model
With data to work on with us, it’s time to move on to the next step of creating
‘Model’ for our web application. To create model, right click on ‘Models’ folder
in Solution Explorer and click on ‘Add>New Item’. Select ‘ADO.NET Entity Data
Model’ template from ‘Data’ category and name it (‘Model1.edmx’). This action
will start Entity Data Model wizard. From ‘Choose Model Contents’, select
‘Generate From Database’. In the second step named ‘Choose Your Data
Connection’, select ‘Database1.mdf’ from new connection drop down window and
name it ‘Dtabase1Entities1’. In the final step (Choose Your Database Object)
select created table(‘Table1’) plus give name to model namespace
(‘Database1Model1’). Once we have created model for our database, it will
display Table1 of Database1 in designer window.

Controller
ASP.NET Controller is to control user interaction with created application. To
add controller to this web application, right click on ‘Controller’ folder in
Solution Explorer and click on ‘Add>Controller’. Name your controller
(Default1Controller) and put a check in front of ‘Add action methods for Create,
Update, and Details scenarios’. Now that we have controller, we need to add code
to this controller. Below is the sample code that is added in ‘Index()’ method,
which is default method of MVC controller. Here we are using Index() method to
display list of products, in this method we used database model created earlier.
‘Database1Entities _entities ‘ class retrieves and stores product records
whereas ‘_entities.Table1.ToList()’ returns list of product records. For
displaying records in browser window, we need to create view for values returned
by Index() method. Build your project and then right click Index() inside
‘Default1Controller.cs’ and click on ‘Add View’. Put check in front of ‘Create a
strongly typed view ‘, select ‘List’ under ‘View content’ drop down and
‘MvcApplication1.Models.Database1Entities’ under ‘View data class’:

Once we have created model for our database, it would
display Table1 of Database1 in designer window.

using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class Default1Controller : Controller
{
private Database1Entities _entities = new Database1Entities();
public ActionResult Index()
{
return View(_entities.Table1.ToList());
}

Press F5 to check output of this web application. Now that we are able to
display records, let’s add few more lines of code to add new records. There are
two create methods inside controller, one without any parameter is used to
display HTML form for creating records whereas create method is called when the
HTML form for creating a new product record is posted to the server. Here is
modified Create() method:

public ActionResult Create()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude="ID")]Table1 Table1create)
{
if (!ModelState.IsValid)
return View();
_entities.AddToTable1(Table1create);
_entities.SaveChanges();
return RedirectToAction("Index");
}

Once code is added, you need to add create view, right click Create() inside
‘Default1Controller.cs’ and click on ‘Add View’. Put check in front of ‘Create a
strongly typed view ‘, select ‘Create’ under ‘View content’ drop down and
‘MvcApplication1.Models.Database1Entities’ under ‘View data class’. When we
again run our application and click on ‘Create New’, it opens up a new page
where we can enter details of new product. One interesting point to note is that
if we try to make any data type mismatch mistake it is highlighted. Next step is
to make changes in our code so that we are able to edit existing records. Here
is the code inside controller under Edit() method :

To view output, right click Index() inside
‘Default1Controller.cs’ and click on ‘Add View’.

public ActionResult Edit(int id)
{
var Table1ToEdit = (from m in _entities.Table1
where m.ID == id
select m).First();
return View(Table1ToEdit);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Table1 Table1ToEdit)
{
var originalTable1 = (from m in _entities.Table1
where m.ID == Table1ToEdit.ID
select m).First();
if (!ModelState.IsValid)
return View(originalTable1);
_entities.ApplyPropertyChanges(originalTable1.EntityKey.EntitySetName,
Table1ToEdit);
_entities.SaveChanges();
return RedirectToAction("Index");

}
}
}

To add view, right click Edit() inside ‘Default1Controller.cs’ and click on ‘Add
View’. Put check in front of ‘Create a strongly typed view ‘, select ‘Edit’
under ‘View content’ drop down and ‘MvcApplication1.Models.Database1Entities’
under ‘View data class’.

Run this application by pressing F5 and now we can not only add records to
our web site but also edit existing records. This was done by just writing few
lines of codes.

No Comments so far

Jump into a conversation

No Comments Yet!

You can be the one to start a conversation.

Your data will be safe!Your e-mail address will not be published. Also other data will not be shared with third person.