CRUD Operation in ASP.Net MVC Framework


Objective:

The core purpose of this article is to demonstrate how to perform CRUD operation on a database in ASP.NET MVC Framework.

See my other articles on ASP.NET MVC Framework to get an understanding of different components of framework.

My articles could be found at

Introduction Here

Output Caching Here

About Controller here

Silverlight in MVC Framework here

Final output would be something like

image1.gif

Data Base Description

  1. I have created one database called ContactDetails in SQL Server 2008.
  2. ContactDetails database contains one table called Author_Contact_Details
  3. Id is a primary key and its (Is Identity) property is set to the value Yes.

    image2.gif

Note: Database script is being attached to download. So either you could run that database script or you could create the database manually by yourself.

Creating MVC application

  1. Open visual studio and create new Project -> Web -> Asp.Net MVC Application.

    image3.gif
     
  2. Create UNIT Test project as well. We will do unit testing on our project later in this article or next series of this article.

    image4.gif
     
  3. After creating application Solution Explorer will look like below. It would contain Model, View and Controller folders.
  4. There will be one more project in solution for Unit Testing.

    image5.gif
     
  5. Delete the following files from the ASP.NET MVC project
    \Controllers\HomeController.cs
    \Views\Home\About.aspx
    \Views\Home\Index.aspx
  6. And delete the following file from the Test project
    \Controllers\HomeControllerTest.cs

Creating the Data Model

  1. Right click on Models and add New Item

    image6.gif
     
  2. From Data tab select Ado.Net Entity data model.
  3. Give any meaningful name for .edmx . Here name is Author_Contact_DetailsModel.

    image7.gif
     
  4. Select "Generate from Database".

    image8.gif
     
  5. Choose Data Source name. Choose Server Name. Select Database.

    image9.gif
     
  6. Click on "Test Connection" to check the connection.

    image10.gif
     
  7. Give Connection string name and click next. Here connection string name is ContactDetailsEntities.

    image11.gif
     
  8. Select table and give model namespace name. Here model namespace name is ContactDetailsModel

    image12.gif

    image13.gif

    At this point, we have created our database model. We can use the Author_Contact_Details class to represent a particular contact record in our database.

Creating the Home Controller

  1. Right click on Controller and select Add Controller.

    image14.gif
     
  2. Give Controller name. Controller name must be post fixed by Controller . Here name is HomeController. You cannot give any name. Controller name must be followed by Controller.
  3. Checked the box to add action methods for Create, Update and Delete When you create the Home controller, you get the class like below

    image15.gif

    Controller\HomeController.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Mvc.Ajax;

    namespace AuthorContactDetail.Controllers
    {
        public class HomeController :
    Controller
        {
           
    //
            // GET: /Home/

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

            //
            // GET: /Home/Details/5

            public ActionResult Details(int id)
            {
                return View();
            }

            //
            // GET: /Home/Create

            public ActionResult Create()
            {
                return View();
            }

            //
            // POST: /Home/Create

            [AcceptVerbs(HttpVerbs.Post)]
            public ActionResult Create(FormCollection collection)
            {
               
    try
                {
                    // TODO: Add insert logic here

                    return RedirectToAction("Index");
                }
               
    catch
                {
                    return View();
                }
            }

            //
           
    // GET: /Home/Edit/5
     
            public ActionResult Edit(int id)
            {
                return View();
            }

            //
            // POST: /Home/Edit/5

            [AcceptVerbs(HttpVerbs.Post)]
            public ActionResult Edit(int id, FormCollection collection)
            {
               
    try
                {
                    // TODO: Add update logic here

                    return RedirectToAction("Index");
                }
               
    catch
                {
                    return View();
                }
            }
        }
    }

    Note: _entities is initialized globally.
     

  4. Now that we've created the Index controller, we next need to create the Index view. Before creating the Index view, compile application by selecting the menu option Build, Build Solution. You should always compile your project before adding a view in order for the list of model classes to be displayed in the Add View dialog.
  5. Right click at Index and select Add View 

    image16.gif
     
  6. Select "Create a Strongly typed view". From View data class select name of the table and in View content select List.

    image17.gif
     
  7. Un modified Index.aspx will look like below

    Views\Home\Index.aspx (unmodified)

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

    <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
    >
                    Id
                </th
    >
                <th
    >
                    FirstName
                </th
    >
                <th
    >
                    LastName
                </th
    >
                <th
    >
                    Phone
                </th
    >
                <th
    >
                    Email
                </th
    >
           </tr>

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

               <tr>
                <td
    >
                    <%= Html.ActionLink("Edit", "Edit", new { id=item.Id }) %> |
                   <%-- <%= Html.ActionLink("Details", "Details", new { id=item.Id })%>--
    %>
                </td
    >
                <td
    >
                    <%= Html.Encode(item.Id)
    %>
                </td
    >
                <td
    >
                    <%= Html.Encode(item.FirstName)
    %>
                </td
    >
                <td
    >
                    <%= Html.Encode(item.LastName)
    %>
                </td
    >
                <td
    >
                    <%= Html.Encode(item.Phone)
    %>
                </td
    >
                <td
    >
                    <%= Html.Encode(item.Email)
    %>
                </td
    >
            </tr>

           <% } %>
     
        </table>

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

     </asp:Content>

    Note: Here, Details Link is commented, because we don't have any details of record.

    Just press F5 to run with debugging.

    image18.gif

Creating New Contacts

If you see at Controller\HomeController.cs, for creating new contacts you will find code below.

// GET: /Home/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Home/Create

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(FormCollection collection)
        {
           
try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
           
catch
            {
                return View();
            }
        }

        //
        // GET: /Home/Edit/5

  1. First Create() action that returns an HTML form for creating a new contact
  2. Second Create () action is performing actual insertion into table.
  3. First Create () action is attributed with HTTP GET verb. So it would return HTML page.
  4. Second Create () action is attributed with HTTP POST verb. So it would post data in database.
  5. Second Create () action could only be called while posting the HTML form.
  6. We need to modify second Create action to perform actual Insertion into database.

    public ActionResult Create()
            {
                return View();
            }

            //
            // POST: /Home/Create

            [AcceptVerbs(HttpVerbs.Post)]
            public ActionResult Create([Bind(Exclude="Id")] Author_Contact_Details contactDetail)
            {

                if (!ModelState.IsValid)
                    return View();
               
    try
                {
                   
    // TODO: Add insert logic here
                    _entities.AddToAuthor_Contact_Details(contactDetail);
                    _entities.SaveChanges();

                    return RedirectToAction("Index");
                }
               
    catch
                {
                    return View();
                }
            }
     

  7. Right click on either of the Create action and add Create View

    image19.gif
     
  8. Select Create a Strongly Typed View and in View Content select Create

    image20.gif
     
  9. Create.aspx file will get created in View/Home. The .aspx will look like below

    View/Home/Create.aspx

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

    <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="Id">Id:</label
    >
                    <%= Html.TextBox("Id")
    %>
                    <%= Html.ValidationMessage("Id", "*")
    %>
                </p
    >
                <p
    >
                    <label for="FirstName">FirstName:</label
    >
                    <%= Html.TextBox("FirstName")
    %>
                    <%= Html.ValidationMessage("FirstName", "*")
    %>
                </p
    >
                <p
    >
                    <label for="LastName">LastName:</label
    >
                    <%= Html.TextBox("LastName")
    %>
                    <%= Html.ValidationMessage("LastName", "*")
    %>
                </p
    >
                <p
    >
                    <label for="Phone">Phone:</label
    >
                    <%= Html.TextBox("Phone")
    %>
                    <%= Html.ValidationMessage("Phone", "*")
    %>
                </p
    >
                <p
    >
                    <label for="Email">Email:</label
    >
                    <%= Html.TextBox("Email")
    %>
                    <%= Html.ValidationMessage("Email", "*")
    %>
                </p
    >
                <p
    >
                    <input type="submit" value="Create"
    />
                </p
    >
            </fieldset>

        <% } %>

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

    </asp:Content>

    Just press F5 to run with debugging.

    image21.gif

    image22.gif

Editing Contacts

If you see at Controller\HomeController.cs , for editing contacts you will find code below.

// GET: /Home/Edit/5

        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /Home/Edit/5

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(int id, FormCollection collection)
        {
           
try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
           
catch
            {
                return View();
            }
        }

  1. The first Edit() method is invoked by an HTTP GET operation. An Id parameter is passed to this method which represents the Id of the contact record being edited. The Entity Framework is used to retrieve a contact that matches the Id. A view that contains an HTML form for editing a record is returned.
  2. The second Edit() method performs the actual update to the database. This method accepts an instance of the Contact class as a parameter. The ASP.NET MVC framework binds the form fields from the Edit form to this class automatically.
  3. Notice that you don't include the [Bind] attribute when editing a Contact (we need the value of the Id property).
  4. We need to modify the Edit action to perform actual operation

    Controller\HomeController.cs

    // GET: /Home/Edit/5

            public ActionResult Edit(int id)
            {

                var res = (from r in _entities.Author_Contact_Details where r.Id == id select r).FirstOrDefault();
                return View(res);
            }

            //
            // POST: /Home/Edit/5

            [AcceptVerbs(HttpVerbs.Post)]
            public ActionResult Edit(Author_Contact_Details contactDetail)
           {

                 if (!ModelState.IsValid)
                    return View();
               
    try
                {
                   
    // TODO: Add update logic here
                    var res = (from r in _entities.Author_Contact_Details where r.Id == contactDetail.Id  select r).FirstOrDefault();
                    _entities.ApplyPropertyChanges(res.EntityKey.EntitySetName, contactDetail);
                    _entities.SaveChanges();

                    return RedirectToAction("Index");
                }
               
    catch
                {
                    return View();
                }
            }
     

  5. Right click at either of Edit action and add View

    image23.gif

     
  6. Create a Strongly typed View. Select table name and in View content select Edit.

    image24.gif

    Just press F5 to run with debugging.

    image25.gif

Deleting Contacts

Controller\HomeController.cs

public ActionResult Delete(int Id)
        {
            var res = (from r in _entities.Author_Contact_Details where r.Id == Id select r).FirstOrDefault();
            return View(res); 
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete(Author_Contact_Details contactDetail)
        {
           
try
            {
                var res = (from r in _entities.Author_Contact_Details where r.Id == contactDetail.Id select r).FirstOrDefault();
                _entities.DeleteObject(res);
                _entities.SaveChanges();
                return RedirectToAction("Index");

            }
           
catch
            {
                return View();
            }

        }

  1. The first Delete() action returns a confirmation form for deleting a contact record from the database.
  2. The second Delete() action performs the actual delete operation against the database. After the original contact has been retrieved from the database, the Entity Framework DeleteObject() and SaveChanges() methods are called to perform the database delete.
  3. In Index.aspx and add below line of code there

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

    Index.aspx

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

    <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
    >
                    Id
                </th
    >
                <th
    >
                    FirstName
                </th
    >
                <th
    >
                    LastName
                </th
    >
                <th
    >
                    Phone
                </th
    >
                <th
    >
                    Email
                </th
    >
            </tr>

        <% foreach (var item in Model) { %>
               <tr
    >
                <td
    >
                    <%= Html.ActionLink("Edit", "Edit", new { id=item.Id }) %> |
                   
    <%= Html.ActionLink("Delete", "Delete", new { id=item.Id })%>
                </td
    >
                <td
    >
                    <%= Html.Encode(item.Id)
    %>
                </td
    >
                <td
    >
                    <%= Html.Encode(item.FirstName)
    %>
                </td
    >
                <td
    >
                    <%= Html.Encode(item.LastName)
    %>
                </td
    >
                <td
    >
                    <%= Html.Encode(item.Phone)
    %>
                </td
    >
                <td
    >
                    <%= Html.Encode(item.Email)
    %>
                </td
    >
            </tr>

           <% } %>

        </table>

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

    </asp:Content>
     

  4. Right click either of Delete action and add View

    image26.gif
     
  5. Create a Strongly typed view and select View content Empty.

    image27.gif

    Just press F5 to run with debugging.

    image28.gif

    image29.gif

Changing the caption of the site

 image30.gif

  1. Go to Views -> Shared -> Site.Master
  2. Change the title and save master page.

    <div id
    ="title">
                    <h1>C# Corner Author's Contact Details</h1
    >
                </div>

    Just press F5 to run with debugging.

    image31.gif

Summary:

This article explained about, how to perform CRUD operation on a table in ASP.Net MVC Framework.

Future Scope:

I will modify sample in this article to accommodate authentication, Ajax etc.

Next Recommended Readings