Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » ASP.NET MVC & JQuery » Building ASP.NET MVC Web Applications using ADO.NET Entity Data Model

Building ASP.NET MVC Web Applications using ADO.NET Entity Data Model

This is a step by step tutorial on how to build ASP.NET MVC Web Applications using ADO.NET Entity Data Model and Visual Studio.

Author Rank :
Page Views : 19277
Downloads : 489
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
MVCUsingADONETEntityDataModel.zip
 
 
Nevron Chart
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Introduction

ASP.NET MVC (Mode-View-Controller) is a free, fully supported, Microsoft product that enables developers to easily build great web applications. It provides total control over your HTML and URLs, enables rich AJAX integration, and facilitates test driven development.

The ASP.NET MVC Framework uses a Model-view-controller pattern. Microsoft added this framework to ASP.NET. It allows software developers to build a Web application as a composition of three roles: Model, View and Controller. A Model represents the state of a particular aspect of the application. Frequently, a model maps to a database table with the entries in the table representing the state of the table. A Controller handles interactions and updates the model to reflect a change in state of the application. A View extracts necessary information from a model and renders a user interface to display that.

Controllers - A controller is responsible for controlling the way that a user interacts with an MVC application. A controller contains the flow control logic for an ASP.NET MVC application. A controller determines what response to send back to a user when a user makes a browser request. A controller is just a class (for example, a Visual Basic or C# class). The sample ASP.NET MVC application includes a controller named HomeController.cs located in the Controllers folder.

Example:

HomeController.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

 

namespace MVCUsingADONETEntityDataModel.Controllers

{

    [HandleError]

    public class HomeController : Controller

    {

        public ActionResult Index()

        {

            ViewData["Message"] = "Welcome to ASP.NET MVC!";

 

            return View();

        }

 

        public ActionResult About()

        {

            return View();

        }

    }

}

 

AccountController.cs

Views - The two controller actions exposed by the HomeController class, Index() and About(), both return a view. A view contains the HTML markup and content that is sent to the browser. A view is the equivalent of a page when working with an ASP.NET MVC application.

You must create your views in the right location. The HomeController.Index() action returns a view located at the following path:
\Views\Home\Index.aspx
The HomeController.About() action returns a view located at the following path:\Views\Home\About.aspx

There are three folders by default in Views:

1.  Account - This folder has four .aspx pages.

  • ChangePassword.aspx

  • ChangePasswordSuccess.aspx

  • LogOn.aspx

  • Register.aspx

2.  Home - It has two folders.

  • About.aspx

  • Index.aspx

3. Shared - It can have asp.net page and user controls and master pages.

  • Error.aspx

  • LogOnUserControl.ascx

  • Site.master

Models - An MVC model contains all of your application logic that is not contained in a view or a controller. The model should contain all of your application business logic, validation logic, and database access logic. For example, if you are using the Microsoft Entity Framework to access your database, then you would create your Entity Framework classes (your .edmx file) in the Models folder.

A view should contain only logic related to generating the user interface. A controller should only contain the bare minimum of logic required to return the right view or redirect the user to another action (flow control). Everything else should be contained in the model.

In general, you should strive for fat models and skinny controllers. Your controller methods should contain only a few lines of code. If a controller action gets too fat, then you should consider moving the logic out to a new class in the Models folder.

Note - You can download ASP.NET MVC framework SDK 1.0 here:

http://www.microsoft.com/downloads/details.aspx?FamilyID=53289097-73ce-43bf-b6a6-35e00103cb4b&displaylang=en

Get Started - After installing MVC framework SDK you will see a new template in installed visual studio templates 'ASP.NET MVC Web Application'.

Create a new project using ASP.NET MVC Web Application -

Figure1.

1.jpg

Next step if you want create unit test project or not? When you create a new ASP.NET MVC application, the Create Unit Test Project dialog appears (see Figure 2). This dialog enables you to create a separate project in your solution for testing your ASP.NET MVC application. Select the option No, do not create a unit test project and click the OK button.

Figure2.

2.jpg

After the new ASP.NET MVC application is created, you will see several folders and files in the solution explorer. There are five folders by default Content, Controllers, Models, Scripts, and Views.

Figure3.

3.jpg

After execution output will look like this.

Figure4.

4.jpg

Now time to add a new item 'ADO.NET Entity Data Model'

Figure5.

5.jpg

In this MVC application I am using NORTHWND database…you can copy that from App_Data folder.

Now generate model from database.

Figure6.

6.jpg

Now choose data connection.

Figure7.

7.jpg 

Now time to choose Database Objects, I have selected Products table you can select multiple tables if you want and click Finish.

Figure8.

8.jpg

ADO.NET Entity Data Model will look like this.

Figure9.

9.jpg
You can rename of model if you want like this. Double click on model name and change name.

Figure10.

10.jpg

So we done with data model here! now let's start work with controllers. Right click on controllers and add a new controller and do check Add action method for Create, Update and Details scenarios, That will add methods for Create, Update and Details.

Figure11.

11.jpg

CustomersController.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Mvc.Ajax;

 

namespace MVCUsingADONETEntityDataModel.Controllers

{

    public class CustomersController : Controller

    {

        //

        // GET: /Customers/

 

        public ActionResult Index()

        {

            return View();

        }

 

        //

        // GET: /Customers/Details/5

 

        public ActionResult Details(int id)

        {

            return View();

        }

 

        //

        // GET: /Customers/Create

 

 

        public ActionResult Create()

        {

            return View();

        }

 

        //

        // POST: /Customers/Create

 

        [AcceptVerbs(HttpVerbs.Post)]

        public ActionResult Create(FormCollection collection)

        {

            try

            {

                // TODO: Add insert logic here

 

                return RedirectToAction("Index");

            }

            catch

            {

                return View();

            }

        }

 

        //

        // GET: /Customers/Edit/5

 

        public ActionResult Edit(int id)

        {

            return View();

        }

 

        //

        // POST: /Customers/Edit/5

 

        [AcceptVerbs(HttpVerbs.Post)]

        public ActionResult Edit(int id, FormCollection collection)

        {

            try

            {

                // TODO: Add update logic here

 

                return RedirectToAction("Index");

            }

            catch

            {

                return View();

            }

        }

    }

}

 

Now right click on Index method and Add View. You need to build your project before adding View.

Figure12.

12.jpg
Now you to select view data class name from drop down list.

Figure13.

13.jpg

Now you have to select View Content type from drop down list. I m going to show products list sho I m selecting List View and click Add.

Figure14.

14.jpg

After that will add a new folder Customers in Views name of Index that will have HTML code like this.

Views/Customers/Index.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MVCUsingADONETEntityDataModel.Models.Products>>" %>

 

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">

      Index

</asp:Content>

 

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

 

    <h2>Index</h2>

 

    <table>

        <tr>

            <th></th>

            <th>

                CategoryID

            </th>

            <th>

                Discontinued

            </th>

            <th>

                ProductID

            </th>

            <th>

                ProductName

            </th>

            <th>

                QuantityPerUnit

            </th>

            <th>

                ReorderLevel

            </th>

            <th>

                SupplierID

            </th>

            <th>

                UnitPrice

            </th>

            <th>

                UnitsInStock

            </th>

            <th>

                UnitsOnOrder

            </th>

        </tr>

 

    <% foreach (var item in Model) { %>

   

        <tr>

            <td>

                <%= Html.ActionLink("Edit", "Edit", new { id=item.ProductID }) %> |

                <%= Html.ActionLink("Details", "Details", new { id=item.ProductID })%>

            </td>

            <td>

                <%= Html.Encode(item.CategoryID) %>

            </td>

            <td>

                <%= Html.Encode(item.Discontinued) %>

            </td>

            <td>

                <%= Html.Encode(item.ProductID) %>

            </td>

            <td>

                <%= Html.Encode(item.ProductName) %>

            </td>

            <td>

                <%= Html.Encode(item.QuantityPerUnit) %>

            </td>

            <td>

                <%= Html.Encode(item.ReorderLevel) %>

            </td>

            <td>

                <%= Html.Encode(item.SupplierID) %>

            </td>

            <td>

                <%= Html.Encode(String.Format("{0:F}", item.UnitPrice)) %>

            </td>

            <td>

                <%= Html.Encode(item.UnitsInStock) %>

            </td>

            <td>

                <%= Html.Encode(item.UnitsOnOrder) %>

            </td>

        </tr>

   

    <% } %>

 

    </table>

 

    <p>

        <%= Html.ActionLink("Create New", "Create") %>

    </p>

 

</asp:Content>

 

Now we need to do some work on Controller class. First of all add a namespace for those models.

using MVCUsingADONETEntityDataModel.Models;

Now you have to make entity model object.

private NORTHWNDEntities _entities = new NORTHWNDEntities();

        //

        // GET: /Customers/

 

        public ActionResult Index()

        {

            return View(_entities.Products.ToList());

        }

And now execute application that will show you default indext page… you need to change the url.

http://localhost:1964/Customers

Output will look like this.

Figure15.

15.jpg 

Now you done with show data using ASP.NET MVC application.

Now let's work on create new product. Almost same this you have to do Add View and select Create View Content and click Add.

Figure16.

16.jpg

Views/Customers/Create.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MVCUsingADONETEntityDataModel.Models.Products>" %>

 

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">

      Create

</asp:Content>

 

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

 

    <h2>Create</h2>

 

    <%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>

 

    <% using (Html.BeginForm()) {%>

 

        <fieldset>

            <legend>Fields</legend>

            <p>

                <label for="CategoryID">CategoryID:</label>

                <%= Html.TextBox("CategoryID") %>

                <%= Html.ValidationMessage("CategoryID", "*") %>

            </p>

            <p>

                <label for="Discontinued">Discontinued:</label>

                <%= Html.TextBox("Discontinued") %>

                <%= Html.ValidationMessage("Discontinued", "*") %>

            </p>

            <p>

                <label for="ProductID">ProductID:</label>

                <%= Html.TextBox("ProductID") %>

                <%= Html.ValidationMessage("ProductID", "*") %>

            </p>

            <p>

                <label for="ProductName">ProductName:</label>

                <%= Html.TextBox("ProductName") %>

                <%= Html.ValidationMessage("ProductName", "*") %>

            </p>

            <p>

                <label for="QuantityPerUnit">QuantityPerUnit:</label>

                <%= Html.TextBox("QuantityPerUnit") %>

                <%= Html.ValidationMessage("QuantityPerUnit", "*") %>

            </p>

            <p>

                <label for="ReorderLevel">ReorderLevel:</label>

                <%= Html.TextBox("ReorderLevel") %>

                <%= Html.ValidationMessage("ReorderLevel", "*") %>

            </p>

            <p>

                <label for="SupplierID">SupplierID:</label>

                <%= Html.TextBox("SupplierID") %>

                <%= Html.ValidationMessage("SupplierID", "*") %>

            </p>

            <p>

                <label for="UnitPrice">UnitPrice:</label>

                <%= Html.TextBox("UnitPrice") %>

                <%= Html.ValidationMessage("UnitPrice", "*") %>

            </p>

            <p>

                <label for="UnitsInStock">UnitsInStock:</label>

                <%= Html.TextBox("UnitsInStock") %>

                <%= Html.ValidationMessage("UnitsInStock", "*") %>

            </p>

            <p>

                <label for="UnitsOnOrder">UnitsOnOrder:</label>

                <%= Html.TextBox("UnitsOnOrder") %>

                <%= Html.ValidationMessage("UnitsOnOrder", "*") %>

            </p>

            <p>

                <input type="submit" value="Create" />

            </p>

        </fieldset>

 

    <% } %>

 

    <div>

        <%=Html.ActionLink("Back to List", "Index") %>

    </div>

 

</asp:Content>

 

Need to change in Create method in controller class.

//

        // GET: /Customers/Create

        public ActionResult Create()

        {

            return View();

        }

        //

        // POST: /Customers/Create

        [AcceptVerbs(HttpVerbs.Post)]

        public ActionResult Create(Products productToCreate)

        {

            try

            {

                // TODO: Add insert logic here

                _entities.AddToProducts(productToCreate);

                _entities.SaveChanges();

                return RedirectToAction("Index");

            }

            catch

            {

                return View();

            }

        }

And now run the the application.

Figure17.

17.jpg

Fill new product detail and press Create button, you will see you record has been inserted in database and that will redirect you on index page.

Figure18.

18.jpg

We done with Create method here now let's start work on Edit method. Same thing you need to do go in controller class and Add View and select strongly-typed view with Edit Content View.

Figure19.

19.jpg

Views/Customers/Edit.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MVCUsingADONETEntityDataModel.Models.Products>" %>

 

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">

      Edit

</asp:Content>

 

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

 

    <h2>Edit</h2>

 

    <%= Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.") %>

 

    <% using (Html.BeginForm()) {%>

 

        <fieldset>

            <legend>Fields</legend>

            <p>

                <label for="CategoryID">CategoryID:</label>

                <%= Html.TextBox("CategoryID", Model.CategoryID) %>

                <%= Html.ValidationMessage("CategoryID", "*") %>

            </p>

            <p>

                <label for="Discontinued">Discontinued:</label>

                <%= Html.TextBox("Discontinued", Model.Discontinued) %>

                <%= Html.ValidationMessage("Discontinued", "*") %>

            </p>

            <p>

                <label for="ProductID">ProductID:</label>

                <%= Html.TextBox("ProductID", Model.ProductID) %>

                <%= Html.ValidationMessage("ProductID", "*") %>

            </p>

            <p>

                <label for="ProductName">ProductName:</label>

                <%= Html.TextBox("ProductName", Model.ProductName) %>

                <%= Html.ValidationMessage("ProductName", "*") %>

            </p>

            <p>

                <label for="QuantityPerUnit">QuantityPerUnit:</label>

                <%= Html.TextBox("QuantityPerUnit", Model.QuantityPerUnit) %>

                <%= Html.ValidationMessage("QuantityPerUnit", "*") %>

            </p>

            <p>

                <label for="ReorderLevel">ReorderLevel:</label>

                <%= Html.TextBox("ReorderLevel", Model.ReorderLevel) %>

                <%= Html.ValidationMessage("ReorderLevel", "*") %>

            </p>

            <p>

                <label for="SupplierID">SupplierID:</label>

                <%= Html.TextBox("SupplierID", Model.SupplierID) %>

                <%= Html.ValidationMessage("SupplierID", "*") %>

            </p>

            <p>

                <label for="UnitPrice">UnitPrice:</label>

                <%= Html.TextBox("UnitPrice", String.Format("{0:F}", Model.UnitPrice)) %>

                <%= Html.ValidationMessage("UnitPrice", "*") %>

            </p>

            <p>

                <label for="UnitsInStock">UnitsInStock:</label>

                <%= Html.TextBox("UnitsInStock", Model.UnitsInStock) %>

                <%= Html.ValidationMessage("UnitsInStock", "*") %>

            </p>

            <p>

                <label for="UnitsOnOrder">UnitsOnOrder:</label>

                <%= Html.TextBox("UnitsOnOrder", Model.UnitsOnOrder) %>

                <%= Html.ValidationMessage("UnitsOnOrder", "*") %>

            </p>

            <p>

                <input type="submit" value="Save" />

            </p>

        </fieldset>

 

    <% } %>

 

    <div>

        <%=Html.ActionLink("Back to List", "Index") %>

    </div>

 

</asp:Content>

 

Put this code in controller class on Edit method click and run the application and click on Edit link button.

//

        // GET: /Customers/Edit/5

        public ActionResult Edit(int id)

        {

            var productToUpdate = _entities.Products.First(m => m.ProductID == id);

            ViewData.Model = productToUpdate;

            return View();

        }

        //

        // POST: /Customers/Edit/5

        [AcceptVerbs(HttpVerbs.Post)]

        public ActionResult Edit(int id, FormCollection collection)

        {  

            // Get product to update

            //var id = Int32.Parse(collection["ProductID"]);

            var productToUpdate = _entities.Products.First(m => m.ProductID == id);

            // Deserialize (Include white list!)

            TryUpdateModel(productToUpdate, new string[] { }, collection.ToValueProvider());

            // Validate

            if (String.IsNullOrEmpty(productToUpdate.ProductName))

                ModelState.AddModelError("ProductName", "ProductName is required!");

            if (ModelState.IsValid)

            {

                // TODO: Add update logic here

                _entities.SaveChanges();

                return RedirectToAction("Index");

            }

            return View(productToUpdate);

        }

 

Output.

Figure20.

20.jpg

Here we have done with Edit. Now we are going to see Delete Method.

Add a new line in Index.aspx

<%= Html.ActionLink("Delete", "Delete", new { id=item.ProductID })%>

Put this method in controller class.

public ActionResult Delete(int id)

        {

            // Get movie to delete

            var productToDelete = _entities.Products.First(m => m.ProductID == id);

 

            // Delete

            _entities.DeleteObject(productToDelete);

            _entities.SaveChanges();

 

            // Show Index view

            return RedirectToAction("Index");

        }

And finally run the application and click on Delete link button that will delete that row from database. If you have any doubt I am attaching my sample application please download this application and if you like this article drop me a comment in c-sharp corner comment section that will encourage the author to write some good articles.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Raj Kumar

Raj Kumar is a Microsoft MVP and Senior Software Engineer with lots of hands on experience using ASP.NET 2.0/3.5, AJAX, MVC, C#, Visual Basic .NET, SQL Server 2005/2008, Oracle, WPF, WCF, XAML and Silverlight. He has over 6 years of IT experience working most on Microsoft technologies. He holds Master's degree in Computer Science. When he is not writing code, he likes to write articles and play cricket.

Reach him at raj2511984@gmail.com 

 

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
DevExpress Free UI Controls
Become a Sponsor
 Comments
Very good article by Mahesh On October 9, 2009
With step by step details. Good work.
Reply | Email | Modify 
Great!!! by Senthilkumar On October 9, 2009
Hey Rajkumar,

Thanks lot for post this articles.

Really it looks good and very good practical approach.

we are expecting the articles like this.

Please continue to share your programming stuffs.


Reply | Email | Modify 
Very Good by Henrique On November 23, 2009
Very good.
I really needed a step by step to embrace MVC.
Thank you.
Reply | Email | Modify 
if you didnt have a integer as ur primary key? how would u impliment the edit function? by sasindra On February 11, 2010
what is the meaning of this line m => m.ProductID == id ?

I mean if your products table didn't have a productID, If it only had a string or varchar type primary key.. how would you edit that model?

Thanks
Dilanka
Reply | Email | Modify 
igonre my previous post by sasindra On February 11, 2010
Heyy sorry plzz ignore my previous post!!!
Reply | Email | Modify 
Error by Jean Paul On October 25, 2010
Hi!
When I add the Edit and Delete Views and run the Web Page, by the moment I click the Edit or Delete link I receive Server Error in '/' Application
Some body know why?
Reply | Email | Modify 
hgmhgmhmhmh by jay On November 15, 2010
hmhgmhgmghmhmghmghmgh
Reply | Email | Modify 
Great Job by victor On December 16, 2010
Hi Raj, Very good Artical.I really needed a step by step to embrace MVC. Thank You Very much.... Reards, Victor....
Reply | Email | Modify 
How to use html5 in mvc by victor On February 9, 2011
Hi Everybody, Any one knows about how to use html5 contrloes in mvc application,please guide me with step by step process thank u Geninus........ Regards , Victor..........
Reply | Email | Modify 
6 Months Free & No Setup Fees ASP.NET Hosting!
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.