Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
World Class ASP.NET Hosting – Click Here for 3 Months Free/NO Setup Fee!
 Resources  
Close
 Our Network  
Close
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:
Total page views :  8594
Total downloads :  185
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
MVCUsingADONETEntityDataModel.zip
 
Become a Sponsor


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.


Login to add your contents and source code to this article
 About the author
 
Raj Kumar
Rajkumar is working as a senior software engineer has over 5 years experience working on ASP.NET, VB.NET, C#, AJAX and other latest technologies. He holds Master's degree in Computer Science. currently enjoying working on WPF, WCF, Silverlight, MVC, XAML.I can be reached on at raj2511984 at yahoo.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.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
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.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
MVCUsingADONETEntityDataModel.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
Very good article by Mahesh On October 9, 2009
With step by step details. Good work.
Reply | Email | Delete | Modify | 
Great!!! by Erode 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 | Delete | 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 | Delete | 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 | Delete | Modify | 
igonre my previous post by sasindra On February 11, 2010
Heyy sorry plzz ignore my previous post!!!
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.