Home > ASP.NET MVC, Entity Framework, EXT JS > Code First Entity Framework and Ext JS in ASP.NET MVC

Code First Entity Framework and Ext JS in ASP.NET MVC

September 11, 2011 Leave a comment Go to comments

Here I am going to describe how we can use Code First Entity Framework and Ext JS in ASP.NET MVC.

First create an ASP.NET MVC 3.0 web application and then we will get the default project template with section for Model, View and Controller.

Model Classes

In MVC application M stands for Model and represents Domain classes. Each class is considered as a Model. We will keep the Model classes in our Model Folder. For a large project you can create a separate project for your Model.
Here are our Model classes in CompanyModel.cs

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

namespace ExtJsMVCExample.Models
{
    public class Company
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string PhoneNumber { get; set; }
        public string Email { get; set; }
        public string Description { get; set; }
    }

    public class Employee
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Address { get; set; }
        public string Sex { get; set; }
        public string Salary { get; set; }
        public DateTime BirthDate { get; set; }
        public DateTime JoinDate { get; set; }
        public Company Company { get; set; }
        public Grade Grade { get; set; }
    }

    public class Grade
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    }
}

Entity Framework Context to Manage Classes and Database interaction

Now we have our Model classes and we will bring the Entity Framework to manage those classes and provide data base interaction.
Before we can use the DbContext, we need to create a reference to the Entity Framework 4.1 API. When installed MVC 3, it added a new feature to Visual Studio 2010 called Nuget. Nuget allows us to easily find and install reference assemblies from the internet.

1. From the Tools Menu, choose Library Package Manager which has a sub-menu.
2. From the sub-menu choose Package Manager Console.
3. At the console’s PM prompt type install-package EntityFramework then hit enter.

The above steps will install the needed package.

Now we will add new class CompanyContext in our Model folder

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace ExtJsMVCExample.Models
{
    public class CompanyContext : DbContext
    {
        public DbSet<Company> Companies { get; set; }
        public DbSet<Employee> EmploEmployees { get; set; }
        public DbSet<Grade> Grades { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Company>().ToTable("Company");
            modelBuilder.Entity<Employee>().ToTable("Employee");
            modelBuilder.Entity<Grade>().ToTable("Grade");

            base.OnModelCreating(modelBuilder);
        }
    }
}

These DbSet properties of the CompanyContext are the key Entity Framework’s ability to execute database queries. As an example, CompanyContext.Employees will execute a query of the Employees table in the database and return a set of Employee object instances based on the Employee class defined earlier.

Controller

So now we need controller to process model data and pass to view. Here I have the controller

CompanyController

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

namespace ExtJsMVCExample.Controllers
{
    public class CompanyController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Companies()
        {
            using (var db = new CompanyContext())
            {
                List<Company> companies = db.Companies.ToList<Company>();
                return Json(companies, JsonRequestBehavior.AllowGet);
            }
        }

    }
}

So if we don’t have the database, the first time hit on the Companies action will create the database for us. Here is my connectionstring in the web.config file.

<add name="CompanyContext"
   connectionString="data source=MIZAN\SQLEXPRESS;Integrated Security=SSPI;
    database=CompanyInformation;  MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" />

For this example consider it has been executed and some data already entered in the company table.

View Company List using Ext JS 4 grid panel

As in http://www.sencha.com/products/extjs/
Ext JS 4 is a major step forward for web frameworks. Building on Ext JS 3.3, our latest release adds over 350 new APIs, 50 new classes, and 65% more documentation. Ext JS 4 also brings an entirely new data package that enables developers to use a model-view-controller architecture when building their app. The new MVC enables apps to leverage features like Infinite Scrolling a Grid to build an entirely new level of interactivity in to web apps.

You can download Sencha Ext JS from here http://www.sencha.com/products/extjs/download/

To start with EXT JS first we need to add reference of ext-all-debug.js and
ext-all.css

Here I have added all the reference in razor layout.cshtml (master) page.

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("~/Content/themes/Extjs/ext-all.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/extjs/ext-all-debug.js")" type="text/javascript"></script>
</head>
<body>
    <div class="page">
        <div id="header">
            <div id="title">
                <h1>
                    Test Application</h1>
            </div>
            <div id="logindisplay">
                @Html.Partial("_LogOnPartial")
            </div>
            <div id="menucontainer">
                <ul id="menu">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                </ul>
            </div>
        </div>
        <div id="main">
            @RenderBody()
        </div>
        <div id="footer">
        </div>
    </div>
</body>
</html>

Now I will display the company list in my Index view and the JS code for this is in company-grid.js

Ext.require([
    'Ext.data.*',
    'Ext.grid.*'
]);

Ext.onReady(function () {

    Ext.define('Company', {
        extend: 'Ext.data.Model',
        fields: ['Id', 'Name', 'Address', 'PhoneNumber', 'Email', 'Description']
    });

    var companyStore = Ext.create('Ext.data.Store', {
        model: 'Company',
        autoLoad: true,
        pageSize: 4,
        proxy: {
            type: 'ajax',
            url: '/company/Companies'
        }
    });


    Ext.create('Ext.grid.Panel', {
        renderTo: 'company_grid',
        store: companyStore,
        width: 800,
        height: 400,
        title: 'Company List',
        columns: [
        {
            text: 'Id',
            width: 100,
            dataIndex: 'Id'
        },
        {
            text: 'Name',
            width: 150,
            dataIndex: 'Name'
        },
        {   
            text: 'Address',
            width: 150,
            dataIndex: 'Address'
        },
        {
            text: 'Pnone Number',
            width: 150,
            dataIndex: 'PhoneNumber'
        },
        {
            text: 'Email',
            flex: 1,
            dataIndex: 'Email'
        },

        {
            text: 'Description',
            flex: 1,
            dataIndex: 'Description'
        }
    ]
    });
});

Now add a reference to the company-grid.js file from the Index view

@{
    ViewBag.Title = "Companies";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<br />
<br />
<div id="company_grid">
</div>
<script src="@Url.Content("~/Scripts/extjs/company-grid.js/")" type="text/javascript"></script>

So now if you hit the …./Company/Index then it will show you the company list.

company list

Advertisements
  1. VJ
    September 26, 2012 at 5:32 am

    Wonderful idea, Very well explain. Thank You.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: