Quantcast
Channel: ASP.NET AJAX + Ajax Control Toolkit (ACT)
Viewing all articles
Browse latest Browse all 5678

CRUD Json and Ajax Can't Edit and delete

$
0
0

good day to all mvcforum,

kindly ask what problem with my code , I can't edit and delete list of my department, please check may code thank you.

Controller

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Business.Models.Department;

namespace Business.Controllers
{
    public class DepartmentController : Controller
    {
        private readonly DepartmentEntities dept = new DepartmentEntities();
        //
        // GET: /Department/
        public ActionResult Index()
        {
            return View();
        }

        // Get dept list
        public ActionResult GetDepartment()
        {

            var tabledept = dept.DEPARTMENTs.ToList();

            return Json(tabledept, JsonRequestBehavior.AllowGet);

        }

        //Get dept by id
        public ActionResult Get(string id)
        {

            var deptdetail = dept.DEPARTMENTs.ToList().Find(i => i.DEPARTMENTID.Trim() == id);

            return Json(deptdetail, JsonRequestBehavior.AllowGet);
        }


        //gagawa yang bagong departamento
        [HttpPost]

        public ActionResult Create(DEPARTMENT department)
        {

            if (ModelState.IsValid)
            {
                dept.DEPARTMENTs.Add(department);
                dept.SaveChanges();

            }

            return Json(department, JsonRequestBehavior.AllowGet);


        }

        //mamamlit yang detalye
        [HttpPost]

        public ActionResult Update(DEPARTMENT department)
        {

            if(ModelState.IsValid)
            {

                dept.Entry(department).State = System.Data.Entity.EntityState.Modified;
                dept.SaveChanges();

            }

            return Json(department, JsonRequestBehavior.AllowGet);

        }


        ///maglako yang departemento
        [HttpPost]

        public ActionResult Delete(string id)
        {

            var deletedept = dept.DEPARTMENTs.ToList().Find(i => i.DEPARTMENTID == id);
            if (deletedept != null)
            {
                dept.DEPARTMENTs.Remove(deletedept);
                dept.SaveChanges();

            }

            return Json(deletedept, JsonRequestBehavior.AllowGet);

        }
    }

}

View

@model IEnumerable<Business.Models.Department.DEPARTMENT>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}<h2 class="w3-content"><b>Departments</b></h2><p class="w3-blockquote w3-content"> List of Departments</p><div class="col-md-10"><br /></div><div class="w3-content"><p><button type="button" id="btnCreate" class="btn btn-default btn-sm" data-toggle="modal" data-target="#departmentModal"><span class="glyphicon glyphicon-plus"></span> Add New</button></p><div class="col-md-12"><br /></div><table id="listdepartment" class="table"><thead><tr class="w3-teal"><th class="w3-text-black"><b>DEPARTMENT ID</b></th><th class="w3-text-black"><b>DEPARTMENT NAME</b></th><th class="w3-text-black"><b>REQUESTLIMIT</b></th><th></th></tr></thead><tbody></tbody></table></div><!--Insert/Update Model--><div id="departmentModal" class="modal fade"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal">&times;</button><h4 class="modal-title"><label id="title"></label></h4></div><div class="modal-body"><div class="form-horizontal"><div class="form-group"><div class="col-md-10"><label>DEPARTMENT ID</label><input type="text" class="form-control" id="DEPARTMENTID" /></div></div><div class="form-group"><div class="col-md-10"><label>DEPARTMENT NAME</label><input type="text" id="DEPARTMENTNAME" class="form-control" /></div></div><div class="form-group"><div class="col-md-10"><label>REQUESTLIMIT</label><input type="number" id="REQUESTLIMIT" class="form-control" /></div></div></div></div><div class="modal-footer"><button type="submit" id="btnSave" class="btn btn-primary">Save</button><button type="button" id="btnClose" class="btn btn-default" data-dismiss="modal">Cancel</button></div></div></div></div><!--Confirmation modal--><div id="confirmModal" class="modal fade"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal">&times;</button><h4 class="modal-title"><label id="title"></label></h4></div><div class="modal-body"><div class="form-horizontal">
                    Do you want to delete this record ?</div></div><div class="modal-footer"><button type="button" id="btnOk" class="btn btn-primary">Ok</button><button type="button" id="btnCancel" class="btn btn-default" data-dismiss="modal">Cancel</button></div></div></div></div>

@section Scripts{

<script type="text/javascript" src="~/Scripts/lib.js"></script>
}
@model IEnumerable<WarehouseRtoRSystem.Models.Department.DEPARTMENT>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}<h2 class="w3-content"><b>Departments</b></h2><p class="w3-blockquote w3-content"> List of Departments</p><div class="col-md-10"><br /></div><div class="w3-content"><p><button type="button" id="btnCreate" class="btn btn-default btn-sm" data-toggle="modal" data-target="#departmentModal"><span class="glyphicon glyphicon-plus"></span> Add New</button></p><div class="col-md-12"><br /></div><table id="listdepartment" class="table"><thead><tr class="w3-teal"><th class="w3-text-black"><b>DEPARTMENT ID</b></th><th class="w3-text-black"><b>DEPARTMENT NAME</b></th><th class="w3-text-black"><b>REQUESTLIMIT</b></th><th></th></tr></thead><tbody></tbody></table></div><!--Insert/Update Model--><div id="departmentModal" class="modal fade"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal">&times;</button><h4 class="modal-title"><label id="title"></label></h4></div><div class="modal-body"><div class="form-horizontal"><div class="form-group"><div class="col-md-10"><label>DEPARTMENT ID</label><input type="text" class="form-control" id="DEPARTMENTID" /></div></div><div class="form-group"><div class="col-md-10"><label>DEPARTMENT NAME</label><input type="text" id="DEPARTMENTNAME" class="form-control" /></div></div><div class="form-group"><div class="col-md-10"><label>REQUESTLIMIT</label><input type="number" id="REQUESTLIMIT" class="form-control" /></div></div></div></div><div class="modal-footer"><button type="submit" id="btnSave" class="btn btn-primary">Save</button><button type="button" id="btnClose" class="btn btn-default" data-dismiss="modal">Cancel</button></div></div></div></div><!--Confirmation modal--><div id="confirmModal" class="modal fade"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal">&times;</button><h4 class="modal-title"><label id="title"></label></h4></div><div class="modal-body"><div class="form-horizontal">
                    Do you want to delete this record ?</div></div><div class="modal-footer"><button type="button" id="btnOk" class="btn btn-primary">Ok</button><button type="button" id="btnCancel" class="btn btn-default" data-dismiss="modal">Cancel</button></div></div></div></div>

@section Scripts{

<script type="text/javascript" src="~/Scripts/lib.js"></script>
}

Script

/*You have to include this js file into Views/Product/Index.cshtml to make the actions on that page works*/$(document).ready(function () {
    getProducts();
});

// Declare a variable to check when the action is Insert or Update
var isUpdateable = false;

// Get products list, by default, this function will be run first for the page load
function getProducts() {
    $.ajax({
        url: '/Department/GetDepartment/',
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            var rows = '';$.each(data, function (i, item) {
                rows += "<tr>"
                rows += "<td>" + item.DEPARTMENTID + "</td>"
                rows += "<td>" + item.DEPARTMENTNAME + "</td>"
                rows += "<td>" + item.REQUESTLIMIT + "</td>"
                rows += "<td><button type='button' id='btnEdit' class='btn btn-default btn-sm' onclick='return getProductById(" + item.DEPARTMENTID + ")'>Edit</button> <button type='button' id='btnDelete' class='btn btn-danger btn-sm' onclick='return deleteProductById(" + item.DEPARTMENTID + ")'>Delete</button></td>"
                rows += "</tr>";$("#listdepartment tbody").html(rows);
            });
        },
        error: function (err) {
            alert("Error: " + err.responseText);
        }
    });
}

// Get product by id
function getProductById(id) {
    $("#title").text("Department Detail");$.ajax({
        url: '/Department/Get/' + id,
        type: 'GET',
        dataType: 'json',
        success: function (data) {$("#DEPARTMENTID").val(data.DEPARTMENTID);$("#DEPARTMENTNAME").val(data.DEPARTMENTNAME);$("#REQUESTLIMIT").val(data.REQUESTLIMIT);
            isUpdateable = true;$("#departmentModal").modal('show');
        },
        error: function (err) {
            alert("Error: " + err.responseText);
        }
    });
}

// Insert/ Update a product
$("#btnSave").click(function (e) {

    var data = {
        DEPARTMENTID: $("#DEPARTMENTID").val(),
        DEPARTMENTNAME: $("#DEPARTMENTNAME").val(),
        REQUESTLIMIT: $("#REQUESTLIMIT").val()
    }

    if (!isUpdateable) {
        $.ajax({
            url: '/Department/Create/',
            type: 'POST',
            dataType: 'json',
            data: data,
            success: function (data) {
                getProducts();$("#departmentModal").modal('hide');
                clear();
            },
            error: function (err) {
                alert("Error: " + err.responseText);
            }
        })
    }
    else {$.ajax({
            url: '/Department/Update/',
            type: 'POST',
            dataType: 'json',
            data: data,
            success: function (data) {
                getProducts();
                isUpdateable = false;$("#departmentModal").modal('hide');
                clear();
            },
            error: function (err) {
                alert("Error: " + err.responseText);
            }
        })
    }
});

// Delete product by id
function deleteProductById(id) {
    $("#confirmModal #title").text("Delete Department");$("#confirmModal").modal('show');$("#confirmModal #btnOk").click(function (e) {$.ajax({
            url: "/Department/Delete/" + id,
            type: "POST",
            dataType: 'json',
            success: function (data) {
                getProducts();$("#confirmModal").modal('hide');
            },
            error: function (err) {
                alert("Error: " + err.responseText);
            }
        });

        e.preventDefault();
    });
}

// Set title for create new
$("#btnCreate").click(function () {$("#title").text("Create New");
})

// Close modal
$("#btnClose").click(function () {
    clear();
});

// Clear all items
function clear() {
    $("#DEPARTMENTID").val("");$("#DEPARTMENTNAME").val("");$("#REQUESTLIMIT").val("");
}

thank you Again


Viewing all articles
Browse latest Browse all 5678

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>