CRUD operations in ASP.NET MVC using Jquery,EF Part 1 ~ MiTechDev.com

Mitechdev.com is a programming blog which focused on Web Programming and development

Thursday, 31 March 2016

CRUD operations in ASP.NET MVC using Jquery,EF Part 1

02:06:00 Posted by raviteja swayampu , , No comments

Introduction:

Hello every one welcome once again.Thanks for your comments for the last post.This article demonstrates "How to implement CRUD operations using Jquery(and Jquery UI also) in ASP.NET MVC with Entity framework".i hope every one knows about the jquery and jqueryUI those are javascript framework libraries for client side web development.Good thing about these is both are "open  source" tools(we need not to pay even a single penny to use).
coming to the article off-course i will explain in step by step manner.i always target the beginners of ASP.NET MVC.
Note: This is a very lengthy article that's why divided this article into two parts PART1 and PART2 for better readability.


Step 1: Create a Visual studio application and database

Note: In this article i am creating table in Sql server express which in-built integrated withVisual studio.If you want to use Another Sql server edition you can use.the procedure is same.

1.create a ASP.NET MVC application using Empty template.
2.right click on App_Start folder -->Add--.New Item-->Select Sql server database-->name it.

CRUD-operations-in-asp.netmvc-using-jquery

3.Create Table: click server explorer-->expand data connections-->expand Database.mdf(name of my database file i added in previous step)-->right click on Table-->Add New Table.then a table designer will appear.
4.create table with name "User".

5.click update button-->in 'Preview Database Updates' window click on "Update Database".
6.User Table created successfully.

Step 2: Add Model class in Model folder

1.right click Model folder-->Add-->New Item-->Select ADO.NET Entity Data Model-->name it Model.edmx.

CRUD-operations-in-asp.netmvc-using-jquery

2.In 'Entity Data Model wizard' select the option 'EF designer from Database'.then click Next

CRUD-operations-in-asp.netmvc-using-jquery
3.select the Database and name the connection string..

CRUD-operations-in-asp.netmvc-using-jquery
4.select the version of Entity Framework 5.0 (EF 6.0 or higher won't support scaffolding).next

5.Select the Table by expanding and click finish.
Now Model class and Context class are created successfully in the Models folder as shown in below.

CRUD-operations-in-asp.netmvc-using-jquery
5.Build the solution once..using Ctrl+Shift+B.
Step 3: Create a Controller

1.create controller and action method for CRUD(create,read,update,delete).
2.right click Controllers folder-->add-->controller-->name it HomeController-->Select 'Empty MVC Controller' from Dropdown. and click ok.
3.Replace HomeController code with following code.

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WvcCrudusingJqueryUI.Models;
namespace WvcCrudusingJqueryUI.Controllers
{
    public class HomeController : Controller
    {
        DatabaseEntities db = new DatabaseEntities();
        public ActionResult Index()
        {
            return View(db.Users.ToList());
        }
        public ActionResult Create()
        {
            return PartialView("Create");
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(User obj)
        {
            if (ModelState.IsValid)
            {
                db.Users.Add(obj);
                db.SaveChanges();
                TempData["msg"] = "Data saved successfully!";
                return RedirectToAction("Index");
            }
            return View();
        }
        public ActionResult Details(int id)
        {
            User record = new User();
            record=db.Users.Find(id);
            if (record == null)
            {
                return HttpNotFound();
            }
            return View(record);
        }
        [HttpGet]
        public ActionResult Edit(int id)
        {
            User record = db.Users.Find(id);
            if (record == null)
            {
                return HttpNotFound();
            }
            return View(record);
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(User obj)
        {
            if (ModelState.IsValid)
            {
                db.Entry(obj).State = EntityState.Modified;
                db.SaveChanges();
                TempData["msg"] = "Data Updated Successfully!";
                return RedirectToAction("Index");
            }
            return View();
        }
        public ActionResult Delete(int id)
        {
            User obj = db.Users.Find(id);
            db.Users.Remove(obj);
            db.SaveChanges();
            TempData["msg"] = "Deleted Successfully";
            return RedirectToAction("index");
        }
    }
}
Step 4: Create Index view
1.Replace code code of Index view with following code
index.cshtml:
@model IEnumerable<WvcCrudusingJqueryUI.Models.User>
@{
    ViewBag.Title = "Index";
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

@* dialog box to diaplay create/edit dialog*@
<div id="create-dialog" style="display:none;"></div>
@* dialog box to diaplay alert after updation of values dialog*@
<div id="alert-dialog" style="display:none;">
    @TempData["msg"]
</div>
@* details dialog*@
<div id="details-dialog" style="display:none;"></div>
@* delete dialog box*@
<div id="delete-dialog" style="display:none">
    Do u want to delete user..
</div>
<h2>Index</h2>
<p>
    @Html.ActionLink("Create New", "Create", null, new { id="lnkCreate"})
</p>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Address)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.ContactNo)
        </th>
        <th>
            Action Operations
        </th>
    </tr>
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Address)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.ContactNo)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id = item.UserID }, new { @class="lnkEdit"}) |
            @Html.ActionLink("Details", "Details", new { id = item.UserID }, new { @class = "lnkDetail" }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.UserID }, new {@class="lnkDelete" })
        </td>
    </tr>
}
</table>
2.Add Jquery libreary files in the Index page.
3.The highlighted <Div> elements to display the partial views like create.update,delete,details (don't worry partial views are nothing but UserControls in traditional ASP.NET Webforms.i will explain those Layout Views and partial views concept later.).
4.Below are links for CRUD operations.when user clicks on these links then popups will appear.

Next : CRUD operations in ASP.NET MVC using Jquery,EF Part 2

Conclusion:
I hope you understand this article.If you recommend any modifications please contact me i am always welcome.very soon i will post part2 article...

0 comments:

Post a Comment