Categories
ASP.net

ការសិក្សាពីរបៀបប្រើប្រាស់ CRUD ជាមួយ Ajax និង Bootstrap ក្នុង ASP.NET MVC 5

មាតិកា

I.   សេចក្តីផ្តើម

II.  គោលបំណង

III. តម្រូវការ

IV. ជំហានទី១៖ បង្កើត Project

V.  ជំហានទី២៖ បង្កើត Database ,Table និង Store Procedure

VI. ជំហានទី៣៖ ធ្វើការបង្កើត Class Model

VII. ជំហានទី៤៖ បង្កើត Controller

VIII. ជំហានទី៥៖ បង្កើត View. 10

IX. ជំហានទី៦៖ បង្កើត file javascript សម្រាប់ធ្វើការជាមួយ ajax

X.  ជំហានទី៨៖ Run Application

I.         សេចក្តីផ្តើម

នៅក្នុង Tutorial នេះ យើងនឹងសិក្សាពីរបៀបប្រើប្រាស់ CRUD ក្នុង ASP.NET MVC ជាមួយនឹង Ajax ។ ខាងក្រោមនេះនឹងបង្ហាញពីជំហាននីមួយៗក្នុងការ implementation កូដ។

II.        គោលបំណង

ក្រោយពីអនុវត្តន៍តាម Tutorial នេះ លោកអ្នកនឹងយល់អំពី

  • យល់ដឹងពីរបៀបបង្កើតនិងប្រើប្រាស់ Ajax
  • យល់ដឹងការបង្កើត Model Controller និង View

III.       តម្រូវការ

ដើម្បីអាចសិក្សា បានយើងត្រូវមាន

  • Microsoft Visual Studio (any version)
  • Microsoft SQL Server (any version)

IV.      ជំហានទី១៖ បង្កើត Project

សូមចូលទៅបើកកម្មវិធី Microsoft visual studio

  • ចុច “Start”
  • បន្ទាប់ “All Programs”
  • ជ្រើសរើសយក “Microsoft Visual Studio 2015”.
  • ដាក់ឈ្មោះអោយ Project
  • ចុច OK
  • រើសយក MVC
  • ចុច OK
  • ក្រោយមកយើងនឹងទទួលបាន Project structure ដូចរូបខាងក្រោម៖

V.         ជំហានទី២៖ បង្កើត Database ,Table និងStore Procedure

សូមចូលទៅបើកកម្មវិធី Microsoft SQL Server 2014

  • right click លើ Database
  • New Database…
  • ក្រោយពីបង្កើត Database រួច សូមធ្វើការបង្កើតTable
  • ចូរបង្កើត Table ដោយប្រើប្រាស់ Script

CREATE TABLE dbo.Employee(

       EmployeeID  int IDENTITY(1,1) NOT NULL,

       Name        nvarchar(50) NULL,

       Age         int NULL,

       State       nvarchar(50) NULL,

       Country     nvarchar(50) NULL,

       CONSTRAINT PK_Employee PRIMARY KEY (EmployeeID)

)

  • បន្ទាប់មកទៀតសូមធ្វើការបង្កើត store procedure ដើម្បីធ្វើ Operation ដូចជា Select, Insert, Update, Delete ខាងក្រោម។

–Select Employees

Create Procedure SelectEmployee

as 

Begin

       Select * from Employee;

End

–Insert and Update Employee

Create Procedure InsertUpdateEmployee

(

       @Id integer,

       @Name nvarchar(50),

       @Age integer,

       @State nvarchar(50),

       @Country nvarchar(50),

       @Action varchar(10)

)

As

Begin

       if @Action=’Insert’

       Begin

Insert into Employee(Name,Age,[State],Country) values(@Name,@Age,@State,@Country);

       End

             if @Action=’Update’

       Begin

Update Employee set Name=@Name,Age=@Age,[State]=@State,Country=@Country where EmployeeID=@Id;

       End

End

–Delete Employee

Create Procedure DeleteEmployee

(

       @Id integer

)

as 

Begin

       Delete Employee where EmployeeID=@Id;

End

VI.         ជំហានទី៣៖ ធ្វើការបង្កើត Class Model

ដើម្បីបង្កើត Model Class បាន ត្រូវ

  • Right click លើ Folder “Models”
  • Add
  • Class
  • បន្ទាប់មកដាក់ឈ្មោះថា “Employee.cs”

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

namespace CRUDAjax.Models

{

    public class Employee

    {

        public int EmployeeID { get; set; }

        public string Name { get; set; }

        public int Age { get; set; }

        public string State { get; set; }

        public string Country { get; set; }

    }

}

  • សូមធ្វើការបង្កើត class model មួយទៀត ដោយដាក់ឈ្មោះថា “EmployeeDB.cs” ដើម្បីធ្វើ Operations។ ក្នុង class នេះយើងប្រើប្រាស់​ ADO.NET ដើម្បីធ្វើការ access data ចេញពី database។

using System;

using System.Collections.Generic;

using System.Configuration;

using System.Data;

using System.Data.SqlClient;

using System.Linq;

using System.Web;

namespace CRUDAjax.Models

{

    public class EmployeeDB

    {

        //declare connection string

        string cs = ConfigurationManager.ConnectionStrings[“DBCS”].ConnectionString;

        //Return list of all Employees

        public List<Employee> ListAll()

        {

            List<Employee> lst = new List<Employee>();

            using (SqlConnection con = new SqlConnection(cs))

            {

                con.Open();

                SqlCommand com = new SqlCommand(“SelectEmployee”, con);

                com.CommandType = CommandType.StoredProcedure;

                SqlDataReader rdr = com.ExecuteReader();

                while (rdr.Read())

                {

                    lst.Add(new Employee

                    {

                        EmployeeID = Convert.ToInt32(rdr[“EmployeeId”]),

                        Name = rdr[“Name”].ToString(),

                        Age = Convert.ToInt32(rdr[“Age”]),

                        State = rdr[“State”].ToString(),

                        Country = rdr[“Country”].ToString(),

                    });

                }

                return lst;

            }

        }

        //Method for Adding an Employee

        public int Add(Employee emp)

        {

            int i;

            using (SqlConnection con = new SqlConnection(cs))

            {

                con.Open();

                SqlCommand com = new SqlCommand(“InsertUpdateEmployee”, con);

                com.CommandType = CommandType.StoredProcedure;

                com.Parameters.AddWithValue(“@Id”, emp.EmployeeID);

                com.Parameters.AddWithValue(“@Name”, emp.Name);

                com.Parameters.AddWithValue(“@Age”, emp.Age);

                com.Parameters.AddWithValue(“@State”, emp.State);

                com.Parameters.AddWithValue(“@Country”, emp.Country);

                com.Parameters.AddWithValue(“@Action”, “Insert”);

                i = com.ExecuteNonQuery();

            }

            return i;

        }

        //Method for Updating Employee record

        public int Update(Employee emp)

        {

            int i;

            using (SqlConnection con = new SqlConnection(cs))

            {

                con.Open();

                SqlCommand com = new SqlCommand(“InsertUpdateEmployee”, con);

                com.CommandType = CommandType.StoredProcedure;

                com.Parameters.AddWithValue(“@Id”, emp.EmployeeID);

                com.Parameters.AddWithValue(“@Name”, emp.Name);

                com.Parameters.AddWithValue(“@Age”, emp.Age);

                com.Parameters.AddWithValue(“@State”, emp.State);

                com.Parameters.AddWithValue(“@Country”, emp.Country);

                com.Parameters.AddWithValue(“@Action”, “Update”);

                i = com.ExecuteNonQuery();

            }

            return i;       

}

//Method for Deleting an Employee

        public int Delete(int ID)

        {

            int i;

            using (SqlConnection con = new SqlConnection(cs))

            {

                con.Open();

                SqlCommand com = new SqlCommand(“DeleteEmployee”, con);

                com.CommandType = CommandType.StoredProcedure;

                com.Parameters.AddWithValue(“@Id”, ID);

                i = com.ExecuteNonQuery();

            }

            return i;

        }

    }

}

VII.         ជំហានទី៤៖ បង្កើត Controller

ដើម្បីបង្កើត Controller Class បាន ត្រូវ

  • Right click លើ Folder “Controller”
  • Add
  • Controller…
  • វានឹង popup ផ្ទាំងមួយទៀតមក
  • សូមយក MVC 5 Controller -Empty
  • ចុច Add
  • ដាក់ឈ្មោះអោយ Controller
  • បន្ទាប់មកទៀតសូមសរសេរកូដខាងក្រោមចូល

using CRUDAjax.Models;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

namespace CRUDAjax.Controllers

{

    public class HomeController : Controller

    {

        EmployeeDB empDB = new EmployeeDB();

        // GET: Home

        public ActionResult  Index()

        {

           return View(empDB.ListAll());

        }

        public JsonResult List()

        {

            return Json(empDB.ListAll(), JsonRequestBehavior.AllowGet);

        }

        public JsonResult Add(Employee emp)

        {

            return Json(empDB.Add(emp), JsonRequestBehavior.AllowGet);

        }

        public JsonResult GetbyID(int ID)

        {

            var Employee = empDB.ListAll().Find(x => x.EmployeeID.Equals(ID));

            return Json(Employee, JsonRequestBehavior.AllowGet);

        }

        public JsonResult Update(Employee emp)

        {

            return Json(empDB.Update(emp), JsonRequestBehavior.AllowGet);

        }

        public JsonResult Delete(int ID)

        {

            return Json(empDB.Delete(ID), JsonRequestBehavior.AllowGet);

        }

    }

}

VIII.         ជំហានទី៥៖ បង្កើត View

បង្កើត view ដើម្បី Add the data

  • សូមធ្វើការ right click ទៅលើ ActionResult Index Method
  • បន្ទាប់មក click “Add View”
  • ក្នុង view ដាក់ឈ្មោះថា “Index.cshtml”
  • សូមធ្វើការសរសេរកូដចូលដូចខាងក្រោម
    • ក្នុង code ខាងក្រោម នៅពេលដែលយើងធ្វើការចុចលើ button​ ដើម្បីធ្វើការ Add New Employee វានឹងបង្ហាញនូវ Modaldialog box របស់ bootstrap ដែលវាមាននូវfields មួយចំនួននៃ employee សម្រាប់ធ្វើការsave data។


   

EmployeesRecord


   


   
       
           
               
               
               
               
               
               
           
       
       
   
IDNameAgeStateCountryAction


 

IX.         ជំហានទី៦៖ បង្កើត file javascript សម្រាប់ធ្វើការជាមួយajax

  • សូមធ្វើការសរសេរកូដខាងក្រោមចូលទៅក្នុង javascript “Employee.js”

//Load Data in Table when documents is ready

$(document).ready(function () {

    loadData();

});

//Load Data function

function loadData() {

    $.ajax({

        url: “/Home/List”,

        type: “GET”,

        contentType: “application/json;charset=utf-8”,

        dataType: “json”,

        success: function (result) {

            var html = ”;

            $.each(result, function (key, item) {

                html += ‘<tr>’;

                html += ‘<td>’ + item.EmployeeID + ‘</td>’;

                html += ‘<td>’ + item.Name + ‘</td>’;

                html += ‘<td>’ + item.Age + ‘</td>’;

                html += ‘<td>’ + item.State + ‘</td>’;

                html += ‘<td>’ + item.Country + ‘</td>’;

                html += ‘<td><a href=”#” onclick=”return getbyID(‘ + item.EmployeeID + ‘)”>Edit</a> | <a href=”#” onclick=”Delele(‘ + item.EmployeeID + ‘)”>Delete</a></td>’;

                html += ‘</tr>’;

            });

            $(‘.tbody’).html(html);

        },

        error: function (errormessage) {

            alert(errormessage.responseText);

        }

    });

}

//Add Data Function

function Add() {

    var res = validate();

    if (res == false) {

        return false;

    }

    var empObj = {

        EmployeeID: $(‘#EmployeeID’).val(),

        Name: $(‘#Name’).val(),

        Age: $(‘#Age’).val(),

        State: $(‘#State’).val(),

        Country: $(‘#Country’).val()

    };

    $.ajax({

        url: “/Home/Add”,

        data: JSON.stringify(empObj),

        type: “POST”,

        contentType: “application/json;charset=utf-8”,

        dataType: “json”,

        success: function (result) {

            loadData();

            $(‘#myModal’).modal(‘hide’);

        },

        error: function (errormessage) {

            alert(errormessage.responseText);

        }

    });

}

//Function for getting the Data Based upon Employee ID

function getbyID(EmpID) {

    $(‘#Name’).css(‘border-color’, ‘lightgrey’);

    $(‘#Age’).css(‘border-color’, ‘lightgrey’);

    $(‘#State’).css(‘border-color’, ‘lightgrey’);

    $(‘#Country’).css(‘border-color’, ‘lightgrey’);

    $.ajax({

        url: “/Home/getbyID/” + EmpID,

        typr: “GET”,

        contentType: “application/json;charset=UTF-8”,

        dataType: “json”,

        success: function (result) {

            $(‘#EmployeeID’).val(result.EmployeeID);

            $(‘#Name’).val(result.Name);

            $(‘#Age’).val(result.Age);

            $(‘#State’).val(result.State);

            $(‘#Country’).val(result.Country);

            $(‘#myModal’).modal(‘show’);

            $(‘#btnUpdate’).show();

            $(‘#btnAdd’).hide();

        },

        error: function (errormessage) {

            alert(errormessage.responseText);

        }

    });

    return false;

}

//function for updating employee’s record

function Update() {

    var res = validate();

    if (res == false) {

        return false;

    }

    var empObj = {

        EmployeeID: $(‘#EmployeeID’).val(),

        Name: $(‘#Name’).val(),

        Age: $(‘#Age’).val(),

        State: $(‘#State’).val(),

        Country: $(‘#Country’).val(),

    };

    $.ajax({

        url: “/Home/Update”,

        data: JSON.stringify(empObj),

        type: “POST”,

        contentType: “application/json;charset=utf-8”,

        dataType: “json”,

        success: function (result) {

            loadData();

            $(‘#myModal’).modal(‘hide’);

            $(‘#EmployeeID’).val(“”);

            $(‘#Name’).val(“”);

            $(‘#Age’).val(“”);

            $(‘#State’).val(“”);

            $(‘#Country’).val(“”);

        },

        error: function (errormessage) {

            alert(errormessage.responseText);

        }

    });

}

//function for deleting employee’s record

function Delele(ID) {

    var ans = confirm(“Are you sure you want to delete this Record?”);

    if (ans) {

        $.ajax({

            url: “/Home/Delete/” + ID,

            type: “POST”,

            contentType: “application/json;charset=UTF-8”,

            dataType: “json”,

            success: function (result) {

                loadData();

            },

            error: function (errormessage) {

                alert(errormessage.responseText);

            }

        });

    }

}

//Function for clearing the textboxes

function clearTextBox() {

    $(‘#EmployeeID’).val(“”);

    $(‘#Name’).val(“”);

    $(‘#Age’).val(“”);

    $(‘#State’).val(“”);

    $(‘#Country’).val(“”);

    $(‘#btnUpdate’).hide();

    $(‘#btnAdd’).show();

    $(‘#Name’).css(‘border-color’, ‘lightgrey’);

    $(‘#Age’).css(‘border-color’, ‘lightgrey’);

    $(‘#State’).css(‘border-color’, ‘lightgrey’);

    $(‘#Country’).css(‘border-color’, ‘lightgrey’);

}

//Valdidation using jquery

function validate() {

    var isValid = true;

    if ($(‘#Name’).val().trim() == “”) {

        $(‘#Name’).css(‘border-color’, ‘Red’);

        isValid = false;

    }

    else {

        $(‘#Name’).css(‘border-color’, ‘lightgrey’);

    }

    if ($(‘#Age’).val().trim() == “”) {

        $(‘#Age’).css(‘border-color’, ‘Red’);

        isValid = false;

    }

    else {

        $(‘#Age’).css(‘border-color’, ‘lightgrey’);

    }

    if ($(‘#State’).val().trim() == “”) {

        $(‘#State’).css(‘border-color’, ‘Red’);

        isValid = false;

    }

    else {

        $(‘#State’).css(‘border-color’, ‘lightgrey’);

    }

    if ($(‘#Country’).val().trim() == “”) {

        $(‘#Country’).css(‘border-color’, ‘Red’);

        isValid = false;

    }

    else {

        $(‘#Country’).css(‘border-color’, ‘lightgrey’);

    }

    return isValid;

}

//saves orderdata in TOrders table

        public JsonResult SaveOrders(TOrder OrdersData)

        {

            bool result = false;

            try

            {

                if (OrdersData != null)

                {

                    using (ASPMVC_DBEntities db = new ASPMVC_DBEntities())

                    {

                        db.TOrders.Add(OrdersData);

                        db.SaveChanges();

                        result = true;

                    }

                }

            }

            catch (Exception ex)

            {

                throw ex;

            }

            return Json(result, JsonRequestBehavior.AllowGet);

        }

    }

}

X.         ជំហានទី៨៖ Run Application

ដើម្បីដំណើរការកម្មវិធី យើងត្រូវ

  • ចូលទៅកាន់ menu
  • រើសយក Debug
  • Start Debugging ឬក៏ Start Debugging Without Debugging
  • ពេលនោះវានឹងដំណើរការ page ឡើងមក
  • ពេលចុចលើប៊ូតុង Add New Employee

សូមធ្វើការបញ្ចូលទិន្នន័យនៅក្នុងform modal

  • បន្ទាប់មកចុចប៊ូតុង Add
  • ក្រោយមកវានឹងបង្ហាញនៅក្នុង list
  • យើងអាចធ្វើការកែប្រែទិន្នន័យដោយចុចលើ Edit

By sysomeho

Ho Sysome obtains B.S. degree in Computer Science from Phnom Penh Internation University (PPIU) in 2013 and currently studying Master of Science in IT (MSIT) at Asia Euro University (AEU). He worked as an IT Officer at Microfinance Institute and Bank in Phnom Penh. He is familar in programming language such as VB.NET, Java (Java2EE, Spring), Codeigniter, Laravel, mysql, sql server and so on. He enjoys sharing knowledges, learns from other, and develop himself.
Find him on Facebook: Spy Ro, Linkedin: Sysome HO.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.