-->

Part 1 - How to implement Basic CRUD Functionality with the Entity Framework and ASP.NET MVC4 application



Introduction

In this post, I am going to show you how to implement Basic CRUD Functionality with the Entity Framework and ASP.NET MVC4 application.
I have split the entire application split into following 3 parts for making things more simple and understandable especially for beginners.

Steps :

Step - 1: Create New Project.

Go to File > New > Project > Select asp.net MVC4 web application > Entry Application Name > Click OK > Select Internet Application > Select view engine Razor > OK

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create 3 tables for store Country, States, and Contact information.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example, I have used 3 tables as below


Contacts

Countries

States

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Create a Folder

Here I have created a folder Named "ExtendedClass" in which we will create a class
Go to Solution Explorer > Right Click on Project name from Solution Explorer > Add > New Folder > Rename Folder.

Step-6: Create a (partial) Class for extending 2 fields CountryName and StateName. Here I have also added MetaData Class for Apply Validation on Contact Model.

Here I have created a (partial) class named "Contact"
Go to Solution Explorer > Right Click on the Folder > Add > Class > Enter class name > Add.

[N:B: I have changed the namespace of the class "MVCCRUD.ExtendedClass" to "MVCCRUD" and make it partial class]
 
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace MVCCRUD
{
    [MetadataType(typeof(ContactMetaData))]
    public partial class Contact
    {
        public string CountryName { get; set; }
        public string StateName { get; set; }
    }

    public class ContactMetaData
    {
        [Required(ErrorMessage="Contact Person required",AllowEmptyStrings=false)]
        [Display(Name="Contact Person")]
        public string ContactPerson { get; set; }

        [Required(ErrorMessage = "Contact No required", AllowEmptyStrings = false)]
        [Display(Name = "Contact No")]
        public string ContactNo { get; set; }

        [Required(ErrorMessage = "Country required")]
        [Display(Name = "Country")]
        public int CountryID { get; set; }

        [Required(ErrorMessage = "State required")]
        [Display(Name = "State")]
        public int StateID { get; set; }
    }

}
    

Step-7: Add a new Controller.

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Step-8: Add new action into your controller for show data in webgrid.

Here I have used "Index" Action for show data. Please write this following code

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

namespace MVCCRUD.Controllers
{
    public class ContactsController : Controller
    {
        //
        // GET: /Contacts/

        public ActionResult Index()
        {
            List<Contact> allContacts = null;
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                var v = (from a in dc.Contacts
                         join b in dc.Countries on a.CountryID equals b.CountryID
                         join c in dc.States on a.StateID equals c.StateID
                         select new
                         {
                             a,
                             b.CountryName,
                             c.StateName
                         });
                if (v != null)
                {
                    allContacts = new List<Contact>();
                    foreach (var i in v)
                    {
                        Contact c = i.a;
                        c.CountryName = i.CountryName;
                        c.StateName = i.StateName;
                        allContacts.Add(c);
                    }
                }
            }
            return View(allContacts);
        }
   }
}
        

Step-9: Add view for the Action & design.

Right Click on Action Method (here right click on form action) > Add View... > Enter View Name > Select View Engine (Razor) > Check "Create a strong-typed view" > Select your model class > Add.
[N:B:Please Rebuild solution before add view.]
Complete View
@model IEnumerable<MVCCRUD.Contact>

@{
    ViewBag.Title = "Index";
    var grid = new WebGrid(source: Model, canPage: true, rowsPerPage: 10);
}

<h2>Contact List</h2>
@Html.ActionLink("Add New Contact", "Save", "Home", null, new{ @style="font-size:20px"})
@grid.GetHtml(
tableStyle:"table table-responsive",
columns:grid.Columns
    (
        grid.Column(columnName:"ContactPerson", header:"Contact Person"),
        grid.Column(columnName:"ContactNo", header:"Contact No"),
        grid.Column(columnName:"CountryName", header:"Country"),
        grid.Column(columnName:"StateName", header:"State"),
        grid.Column(header:"Edit", format:@<text>@Html.ActionLink("Edit", "Save", "Home", new { id= item.ContactID}, null)</text>),
        grid.Column(header:"Delete", format:@<text>@Html.ActionLink("Delete", "Delete", "Home", new { id= item.ContactID}, null)</text>)
    )
)
        
Optional: Here I have added Bootstrap css in the layout page for Responsive design.

Step-10: Run Application.





Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.