Click here to Skip to main content
15,881,380 members
Articles / Entity Framework / Entity Framework 5.0

ASP.NET MVC-4,Entity Framework and JQGrid Demo with simple Todo List WebApplication

Rate me:
Please Sign up or sign in to vote.
4.88/5 (40 votes)
5 Aug 2014CPOL10 min read 261.6K   69   56
Asp.Net MVC-4,Entity Framework and JQGrid Demo with simple Todo List WebApplication

Learn And Build Web Application using MVC and EntityFramework

https://www.youtube.com/watch?v=GanjklfebEc&index=1&list=PLdmgFSerzv2Kl00tz0qY-jxDPnPowpRaT

Overview

          TodoList is a simple web application to create, store and modify Todo tasks to be maintained by the users, which comprises of following fields to the user (Task Name, Task Description, Severity, Target Date, Task Status). 

          TodoList web application is created using MVC - 4 architecture, code-first Entity Framework (ORM) and Jqgrid for displaying the data.

Image 1

 

Source Code

 

You can download the source code from  https://dotnetsourcedileep.codeplex.com/

 

I am dividing this topic in to 2 sections.

Section 1: contains basic theoretical details of the technologies that we are used and the advantages of using ASP.net MVC-4, Code first Entity Framework and JQgrid technologies.

videohttps://www.youtube.com/watch?v=OhJtxRvgeK0

Section 2: contains the practical implementation of step by step creating a simple TodoList application using ASP.net MVC-4, Code first Entity Framework and JQgrid.

video: https://www.youtube.com/watch?v=d-d4C2SVAYQ

Section 3:  JQGrid and MVC Demo with Custom Filters or Search Functionality:

http://www.codeproject.com/Tips/825724/Section-JQGrid-and-MVC-Demo-with-Custom-Filters-or

-----------------------------------------------------------------------------------------------------------------------------

 

Section 1:

MVC

  • MVC is a pattern for developing applications that are well architected and easy to maintain. So using MVC we can develop testable, flexible, scalable, extensible standard based applications.
  • MVC is not a replacement of Asp.net web forms based development. This sits on top of Asp. net development. MVC framework is defined in "System.Web.MVC.Assembly".
  • MVC works on Conventions over configurations.

Model

  • Model represents the application data domain. It can contain a logic related to data domain.In short the application business logic is contained with in the model.
  • Model contains a pieces of C# classes with set of properties and validations defined on top of it using data annotations. It can also contain data access, data aggregation logic etc.
  • Model can be entities or business logic.

View

  • View represents the presentation layer of the web applications.
  • View manages the display of information based on the data of the model i.e. requested by the controller.
  • View Represents the User interface, with which the end user interacts. In short all the UI related logic is contain the View.

Controller

  • Controller handles the user interaction with the web application.
  • User requests comes through the controller to model and manipulates the records from it and render the data using view to UI.
  • Controller contains the control flow logic.
  • Controller contains the set of action methods.

Why MVC or Advantages of Using MVC

There are many advantages of using MVC as follows: -

  • MVC helps us to develop loosely coupled architecture.
  • Complex applications can be easily managed.
  • Separations of concerns is possible by dividing the application in to Model,View and Controller.
  • Extensive support for Test Driven Development(TDD). Unit testing will be easy, an additional layer of testing will provide yet another layer of defense against unexpected behavior.
  • Asp. net MVC is light weight as they do not use view state.
  • SEO(Search Engine Optimization) Clean Url's and no extension methods are used for locating the physical files.
  • Rich javascript support with UnObstrusive javascript, Jquery Validation with Json binding.
  • No Post back events.
  • Expressive views including the new Razor view engine and HTML - 5 enabled.

Entity Framework

       The Microsoft ADO.Net Entity Framework is an Object Relational Mapping (ORM) framework that enables developers to work with relational data as a domain specific object, eliminating the use of most of the data access plumbing code that developers usually need to write.

Code First Approach

      Code First is mainly used in Domain Driven Design(DDD) approach. We can focus on the domain design and start writing the classes as per the domain requirement rather than design the database first and then you create the classes that matches your database design. Code first API's will create the database on the fly based on your entity classes and configuration.

Why Entity Framework?

Basically in the real world scenarios there are 2 types of groups or models will be present like Logical Data Model and Object Oriented Domain Model

Logical Data Model

Almost any business application today as to speak to a relational database. These relational database can also say it has a Backend SQLSERVER contains all the Stored Procedures, tables with foreign key, view etc. Which will be handled by 1 group of people called as database centric.

Object Oriented Domain Model 

Applications are developed completely different from the logical data model. These Object Oriented Domain Model deals with objects, behaviors, properties, inheritance, polymorphic etc. Which will be handled by 1 group of people called as application centric.

Impedence Mismatch

As a result of above 2 models impedance mismatch occurs, as the developers devote a lot of time and energy writing code to translate between how the database likes to see the data and how the application likes to see the data.

 

So Ado .net Entity Framework seeks to remedy to problem by providing the layer of abstraction between the logical data model and the application domain model.

Advantages of using Entity Framework

  • Entity framework enables developers to create data access application by programming against conceptual application model instead of programming against relational storage schema.
  • Application can work in terms of more application centric conceptual model including types with inheritance, complex members and relationships.
  • Entity framework is an ORM tool that provide simple API to perform CRUD operations. IT helps us to automatically work on DML and DDL operations from the front end, instead of going and doing it manually from the back end.
  • Entity framework provides strongly typed classes, giving intellisense support, compile time and debugger options.
  • Plumbing and mapping is done for you. So developers need not to write most of the data access plumbing code that normally required(e.g.ADO.net)
  • Lot of time will be saved and it helps us to quickly develops the application and concentrate more on business centric details.

JQGRID

Jqgrid is an ajax enabled javascript control that provides solution for representing and manipulation tabular data on the grid. Since grid is a client side solution loading data dynamically through ajax call backs, it can be integrated with any server side technology, including php, ASP java servelets, JSP and perl.

 

JQGrid uses Jquery javascript library.

Requirements

  • JQGrid plugin
  • Jquery library, version 1.1.4 or above.
  • web browser
  • data can be stored in xml, json
  • a web server (IIS, Apche, Tomcat)
    a db backend (SQL Server, Oracle MSSql )
    a server side scripting language( PHP, ASP)

JQGrid is a component that helps you in an easy way to represent database information on the client side using a server side technology. Moreover that helps you to manipulate data back in to database.

Features of JQGrid

  • JQGrid helps us to develop most browser compatibility web pages and also supports cross browser support functionality.
  • CSS based themes. Developers can change the grid skin by defining their own UI CSS framework.
  • The new rendering engine is 5-10 times faster loading speed then the previous.
  • Pagination functionality is present. So no need to retrieve all the data from the server.
  • Sorting, Various data types and sub grid support functionality.
  • Event handlers and User API.
  • Formatter supports advanced formating of the contents of the cell in the required format in the client side itself.
  • Inline Editing: easy to update the cell content in a particular row.
  • Searching and filtering.
  • Import and Export data.

 

Section 2:

Creating simple TodoList application using MVC-4, Code-first Entity Framework and Jqgrid.

  • Create a new MVC 4 Web application.
  • Give the Name of the application and click on OK.

Image 2

 

  • Select a required template and the view engine.

Image 3

 

 

  • Open a layout page present inViews ->Shared ->_Layout.cs page and add a new Action Link for TODOLIST tab.
<li>@Html.ActionLink("TodoList", "Index", "TodoList")</li>
  • This action link is for TodoList tab in the menu.
JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title - Todo List Application</title>
    <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
    <meta name="viewport" content="width=device-width" />
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    <header>
        <div class="content-wrapper">
            <div class="float-left">
                <p class="site-title">@Html.ActionLink("your logo here", "Index", "Home")</p>
            </div>
            <div class="float-right">
                <section id="login">
                    @Html.Partial("_LoginPartial")
                </section>
                <nav>
                    <ul id="menu">
                        <li>@Html.ActionLink("Home", "Index", "Home")</li>
                        <li>@Html.ActionLink("About", "About", "Home")</li>
                        <li>@Html.ActionLink("TodoList", "Index", "TodoList")</li>
                        <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                    </ul>
                </nav>
            </div>
        </div>
    </header>
    <div id="body">
        @RenderSection("featured", required: false)
        <section class="content-wrapper main-content clear-fix">
            @RenderBody()
        </section>
    </div>
    <footer>
        <div class="content-wrapper">
            <div class="float-left">
                <p>&copy; @DateTime.Now.Year - My ASP.NET MVC Application</p>
            </div>
        </div>
    </footer>

    @Scripts.Render("~/bundles/jquery")
    @RenderSection("scripts", required: false)
</body>
</html>
  • Goto tools -> Library Package Manager -> Package Manger Console.
  • Install entity framework - 5 in package manager console.

Image 4

 

  • Right Click on References and click on Manage Nuget.
  • Search for Jqgrid and select JQueryJQGrid and install it.

Image 5

 

  • Add a TodoList class file in the Model for storing entities.

Image 6

 

  • Open -> "TodoList.cs" and add the required Entities to the TodoList model class.
  • Todo List contailns all the properties that are used in the screen.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TodoListDemoApplication.Models
{
    public class TodoList
    {
        public int Id { get; set; }
        public string TaskName { get; set; }
        public string TaskDescription { get; set; }
        public DateTime TargetDate { get; set; }
        public string Severity { get; set; }
        public string TaskStatus { get; set; }
    }
}
  • Add a DBContext folder to the solution and add a "TodoContext cs" class.

Image 7

 

 

 

  • Created TodoContext acts like a bridge or acts like a connection object between database and the LinqObject which will be similar to Ado.net connection object.
  • Add a DbseDbSet represents the tables which will be present in the database.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using TodoListDemoApplication.Models;

namespace TodoListDemoApplication.DBContext
{
    public class TodoContext:DbContext
    {
        public DbSet<TodoList> TodoLists { get; set; }
    }
  • Modify the Connection String in the web.config file and the name will be Context Name (TodoContext) which we have created it.
  • Also give the proper conncetion string details like data source, Initial catalog and provider name etc.
<connectionStrings>
<add name="TodoContext" 
     connectionString="Data Source=(Local);Initial Catalog=TodoListDemo;Integrated Security=SSPI;"
     providerName="System.Data.SqlClient" />
</connectionStrings>
  • Goto Package Manager Console.
  • Enable the migrations for using Code First Code Migrations approach by exceuting command "EnableMigrations -ContextTypeName ContextName".
  • Code-First Migrations will take care of the data while during schema modifications. So we no need to write the "dropcreate database" methods that was required to be handled by the developers in earlier old version of Entity frame work.

Image 8

 

  • Once after enabling the migrations for the particular context that we are using, next step is to Add Migration.
  • Execute "Add-Migration" command in package mangaer console. This will generate Migration file, sql code and this will not be executed in SQL Server unless and untill we run "update-database" command.

Image 9

 

  • Code Migration File Generated.

Image 10

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • "update-database" command will seed the database by running the code which is present in the code migration file.

Image 11

 

Image 12

 

  • Open the Sql Server and check the database and the table which got automatically generated using code migration Entity framework approach.

Image 13

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • Add a Todolist Controller.

Image 14

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • Add a view to index action method.

Image 15

 

  • View has been added.

Image 16

 

  • Add a TodoList javascript file.

Image 17

 

  • "GetTodoLists" is a action method that will render the list of all the Todo list to the JQGrid with sorting and paging implemented in the action method.

Image 18

 
  • JQGrid functionality code is added in a TodoList.js file which will be placed inside the Jquery ready function

Image 19

 

  • Few important JQGrid property details that normally used with explanation.

Image 20

 

  • Add the required Jquery, Jqgrid script reference in the index page in the following order.

Image 21

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • Remove the jquery reference in the layout file to avoid the conflict.

Image 22

 

  • Run the application, we will should be able to see the Jqgrid.
  • Next step is to implement CRUD functionality in JQGrid.

Image 23

 

  • Add navGrid functionality with CRUD operations implemented in JQGrid present in "TodoList.Js" file.

Image 24

Image 25

Image 26

 

  • Create is a HTTP Post  action method in TodoList Controller for creating the Todo List.
  • Entity framework is been used for inserting in to the database avoiding the use of ado.net mechanism.
  • Internally Entity frame Work will generate the query and run in the database only after SaveChanges method is been called.
  • "ModelState.IsValid" is used to validate the model. "ModelState.IsValid" will return true if all the model validations are satisfied in the server-side, else returns false and will not allow to execute the further code.

Image 27

 

  • Edit action method is used to update the edited Todo List row in the JQGrid.
  • Delete action method is used to delete the selected Todo List row in the JQGrid.

Image 28

 
  • JQGrid now with the CRUD functionality implemented present in the Page navigator.

Image 29

 
  • Lets add 1 task item to the Todo List by clicking on + button present in the Page navigator.

Image 30

 

  • Submit the data after entering the valid data will save the data into the JQGrid.

Image 31

 
  • Editing one of the Todo List in the JQGrid.

Image 32

 

  • Target date updated successfully in the JQGrid.

Image 33

 

  • Deleting 1 of the Todo List task(task 5) in the JQGrid.

Image 34

Image 35

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer HP
India India
I am working in HP as a dot net developer.Working in .net technologies(MVC,Entityframework,LINQ,Jquey

Comments and Discussions

 
QuestionWhat about EF Database First? Pin
Juba18-Sep-17 5:43
Juba18-Sep-17 5:43 
Questionparameter Pin
Member 131603009-May-17 20:03
Member 131603009-May-17 20:03 
Questionclient side sorting Pin
Member 1292811230-Dec-16 2:50
Member 1292811230-Dec-16 2:50 
QuestionFirst screen problem Pin
Rajat Srivastava1-Dec-16 7:38
Rajat Srivastava1-Dec-16 7:38 
Questiondatabase reg:- Pin
Bala100716-Oct-16 21:40
Bala100716-Oct-16 21:40 
GeneralMy vote of 1 Pin
Bala100716-Oct-16 21:37
Bala100716-Oct-16 21:37 
GeneralMy vote of 1 Pin
Bala100714-Oct-16 4:38
Bala100714-Oct-16 4:38 
QuestionBuild Error Pin
ChandiniVoddi18-Sep-16 4:10
ChandiniVoddi18-Sep-16 4:10 
Generalthank you comment Pin
harshil gandhi8-Jun-16 2:40
harshil gandhi8-Jun-16 2:40 
BugFor some reason on create and edit the data is not being passed to the controller? Pin
jay crowe27-Nov-15 1:59
jay crowe27-Nov-15 1:59 
Generaljqgrid Pin
sooraj7116-Sep-15 19:57
sooraj7116-Sep-15 19:57 
QuestionJqgird Pin
Member 1192123925-Aug-15 7:55
Member 1192123925-Aug-15 7:55 
QuestionMicrosoft EF6 MVC5 support EF optimistic concurrency exceptions. Pin
Gorlov22-Apr-15 11:17
Gorlov22-Apr-15 11:17 
QuestionThe parameters dictionary contains a null entry for parameter 'page' of non-nullable type 'System.Int32' Pin
nischalinn20-Apr-15 6:03
nischalinn20-Apr-15 6:03 
QuestionDB FIRST JQGRID IN MVC 5 & EF 6 Pin
Samuel Fentahuen13-Apr-15 9:47
Samuel Fentahuen13-Apr-15 9:47 
can you please share us DB first of this project with Mvc 5 and EF 6?

QuestionEdit is not working. Pin
Member 1085816214-Mar-15 19:27
Member 1085816214-Mar-15 19:27 
QuestionFailed to load resource: the server responded with a status of 500 (Internal Server Error) Pin
Pratham495013-Mar-15 3:54
Pratham495013-Mar-15 3:54 
AnswerRe: Failed to load resource: the server responded with a status of 500 (Internal Server Error) Pin
Member 1085816214-Mar-15 19:25
Member 1085816214-Mar-15 19:25 
QuestionSub Grid functionality Pin
m.tahsildari28-Feb-15 4:03
m.tahsildari28-Feb-15 4:03 
AnswerRe: Sub Grid functionality Pin
Dileep Ashok28-Feb-15 5:30
professionalDileep Ashok28-Feb-15 5:30 
GeneralMy vote of 5 Pin
Manika Agarwal23-Feb-15 20:24
Manika Agarwal23-Feb-15 20:24 
GeneralMy vote of 5 Pin
iSahilSharma13-Feb-15 0:49
iSahilSharma13-Feb-15 0:49 
QuestionNice Article Pin
SHIVA143429-Dec-14 18:19
SHIVA143429-Dec-14 18:19 
AnswerRe: Nice Article Pin
Dileep Ashok28-Feb-15 5:31
professionalDileep Ashok28-Feb-15 5:31 
QuestionHow to bind complex object to the controller? Pin
profendre7-Dec-14 11:12
profendre7-Dec-14 11:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.