Categories
ASP.net

ការសិក្សាពីរបៀបបង្កើត CRUD ក្នុង ASP.NET MVC 5

មាតិកា

  1. សេចក្តីផ្តើម
  2. គោលបំណង
  3. តម្រូវការ
  4. ជំហានទី១៖ បង្កើត Project
  5. ជំហានទី២៖ បង្កើត Database និង Table
  6. ជំហានទី៣៖ បង្កើត Class Model
  7. ជំហានទី៤៖ បង្កើត Controller
  8. ជំហានទី៥៖ បង្កើត Repository folder និង Repository Class
  9. ជំហានទី៦៖ បង្កើត Method នៅក្នុង EmployeeController.cs file
  10. ជំហានទី៧៖ បង្កើត View
  11. ជំហានទី៨៖ ធ្វើការ Configure ActionLink ទៅលើ Edit និង delete records
  12. ជំហានទី៩៖ Configure RouteConfig.cs ដើម្បី set default action
  13. ជំហានទី១០៖ Run Application

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

នៅក្នុង Tutorial នេះ យើងនឹងសិក្សាពីរបៀបង្កើត create, read, update, និង delete ជាមួយ ASP.NET MVC5។ ខាងក្រោមនេះនឹងបង្ហាញពីជំហាននីមួយៗក្នុងការ implementation កូដ។

2. គោលបំណង

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

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

3. តម្រូវការ

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

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

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

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

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

5. ជំហានទី២៖ បង្កើត Database និង Table

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

  • right click លើ Database
  • New Database…
  • ក្រោយពីបង្កើត Database រួច សូមធ្វើការបង្កើត Table
  • Right click លើ Table
  • New
  • Table…
  • សូមបង្កើត Column ដូចរូប
  • ចូរបង្កើត Store Procedure ដូចខាងក្រោម
    • Store Procedure សម្រាប់ Insert Records
      Create procedure [dbo].[AddNewEmpDetails]
      (
      @Name varchar (50),
      @City varchar (50),
      @Address varchar (50)
      )
      as
      begin
      Insert into Employee values(@Name,@City,@Address)
      End
    • Store Procedure សម្រាប់ View Records
      Create Procedure [dbo].[GetEmployees]  
      as  
      begin  
         select *from Employee  
      End
    • Store Procedure សម្រាប់ Update Records
      Create procedure [dbo].[UpdateEmpDetails]  
      (  
         @EmpId int,  
         @Name varchar (50),  
         @City varchar (50),  
         @Address varchar (50)  
      )  
      as  
      begin  
         Update Employee   
         set Name=@Name,  
         City=@City,  
         Address=@Address  
         where Id=@EmpId  
      End
    • Store Procedure សម្រាប់ Delete Records
      Create procedure [dbo].[DeleteEmpById]  
      (  
         @EmpId int  
      )  
      as   
      begin  
         Delete from Employee where Id=@EmpId  
      End

6. ជំហានទី៣៖ បង្កើត Class Model

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

    • Right click លើ Folder “Models”
    • Add
    • Class…
    • វានឹងលោតផ្ទាំងមួយទៀត

  • ដាក់ឈ្មោះអោយ Model class
  • Click “Add”
  • យើងនឹងទទួលបាន class model​ ខាងក្រោម
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace ASPMVCEmployee.Models
    {
        public class EmpModel
        {
        }
    }
  • បន្ទាប់មកសូមធ្វើការបង្កើតនូវ Class Properties ព្រមទាំង dataAnnotations​ របស់វា
    using System.Linq;
    using System.Web;
    
    namespace ASPMVCEmployee.Models
    {
        public class EmpModel
        {
            [Display(Name="Id")]
            public int Empid { get; set; }
            [Required (ErrorMessage ="First name is required.")]
            public string Name { get; set; }
            [Required(ErrorMessage = "City is required.")]
            public string City { get; set; }
            [Required(ErrorMessage = "Address is required.")]
            public string Address { get; set; }
        }
    }

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

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

  • Right click លើ Folder “Controller”
  • Add
  • Controller…
  • វានឹង popup ផ្ទាំងមួយទៀតមក

  • សូមយក MVC 5 Controller with read/write actions
  • ចុច Add
  • ដាក់ឈ្មោះអោយ Controller
  • យើងនឹងទទួលបាន class controller ជាមួយ action របស់វាដូចខាងក្រោម
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace ASPMVCEmployee.Controllers
    {
        public class EmployeeController : Controller
        {
            // GET: Employee
            public ActionResult Index()
            {
                return View();
            }
            // GET: Employee/Details/5
            public ActionResult Details(int id)
            {
                return View();
            }
            // GET: Employee/Create
            public ActionResult Create()
            {
                return View();
            }
            // POST: Employee/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
            // GET: Employee/Edit/5
            public ActionResult Edit(int id)
            {
                return View();
            }
            // POST: Employee/Edit/5
            [HttpPost]
            public ActionResult Edit(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add update logic here
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
            // GET: Employee/Delete/5
            public ActionResult Delete(int id)
            {
                return View();
            }
            // POST: Employee/Delete/5
            [HttpPost]
            public ActionResult Delete(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add delete logic here
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
        }
    }

8. ជំហានទី៥៖ បង្កើត Repository folder និង Repository Class

យើងបង្កើត Folder repository និង repository ក្នុងគោលបំណងផ្ទុកនូវ database operations ដូចជា method crud ជាដើម។

    • Right click លើ project
    • Add
    • New Folder
    • សូមបង្កើត class repository
    • យើងនឹងទទួលបានដូចរូប

  • សូមធ្វើការសេរសេរកូដនៅក្នុង class “EmpRepository.cs”
    using ASPMVCEmployee.Models;
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Web;
    
    namespace ASPMVCEmployee.Repository
    {
        public class EmpRepository
        {
            private SqlConnection con;
            //To Handle connection related activities    
            private void connection()
            {
                string constr = ConfigurationManager.ConnectionStrings["getconn"].ToString();
                con = new SqlConnection(constr);
            }
            //To Add Employee details    
            public bool AddEmployee(EmpModel obj)
            {
                connection();
                SqlCommand com = new SqlCommand("AddNewEmpDetails", con);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@Name", obj.Name);
                com.Parameters.AddWithValue("@City", obj.City);
                com.Parameters.AddWithValue("@Address", obj.Address);
                con.Open();
                int i = com.ExecuteNonQuery();
                con.Close();
                if (i >= 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            //To view employee details with generic list     
            public List<EmpModel> GetAllEmployees()
            {
                connection();
                List<EmpModel> EmpList = new List<EmpModel>();
                SqlCommand com = new SqlCommand("GetEmployees", con);
                com.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter da = new SqlDataAdapter(com);
                DataTable dt = new DataTable();
                con.Open();
                da.Fill(dt);
                con.Close();
                //Bind EmpModel generic list using dataRow     
                foreach (DataRow dr in dt.Rows)
                {
                    EmpList.Add(
                        new EmpModel
                        {
                            Empid = Convert.ToInt32(dr["Id"]),
                            Name = Convert.ToString(dr["Name"]),
                            City = Convert.ToString(dr["City"]),
                            Address = Convert.ToString(dr["Address"])
                        }
                     );
                }
                return EmpList;
            }
    //To Update Employee details    
            public bool UpdateEmployee(EmpModel obj)
            {
                connection();
                SqlCommand com = new SqlCommand("UpdateEmpDetails", con);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@EmpId", obj.Empid);
                com.Parameters.AddWithValue("@Name", obj.Name);
                com.Parameters.AddWithValue("@City", obj.City);
                com.Parameters.AddWithValue("@Address", obj.Address);
                con.Open();
                int i = com.ExecuteNonQuery();
                con.Close();
                if (i >= 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            //To delete Employee details    
            public bool DeleteEmployee(int Id)
            {
                connection();
                SqlCommand com = new SqlCommand("DeleteEmpById", con);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@EmpId", Id);
                con.Open();
                int i = com.ExecuteNonQuery();
                con.Close();
                if (i >= 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
    }
  • ចំណាំ៖

string constr = ConfigurationManager.ConnectionStrings[“getconn”].ToString();

សូមដាក់ឈ្មោះ Connection អោយដូចនៅក្នុង Web.config

 

9. ជំហានទី៦៖ បង្កើត Method នៅក្នុង EmployeeController.cs file

  • បើក file “EmployeeController.cs”
  • សរសេរកូដចូល
    using ASPMVCEmployee.Models;
    using ASPMVCEmployee.Repository;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace ASPMVCEmployee.Controllers
    {
        public class EmployeeController : Controller
        {
            // GET: Employee/GetAllEmpDetails    
            public ActionResult GetAllEmpDetails()
            {
                EmpRepository EmpRepo = new EmpRepository();
                ModelState.Clear();
                return View(EmpRepo.GetAllEmployees());
            }
            // GET: Employee/AddEmployee    
            public ActionResult AddEmployee()
            {
                return View();
            }
            // POST: Employee/AddEmployee    
            [HttpPost]
            public ActionResult AddEmployee(EmpModel Emp)
            {
                try
                {
                    if (ModelState.IsValid)
                    {
                        EmpRepository EmpRepo = new EmpRepository();
    
                        if (EmpRepo.AddEmployee(Emp))
                        {
                            ViewBag.Message = "Employee details added successfully";
                        }
                    }
                    return View();
                }
                catch
                {
                    return View();
                }
            }
            // GET: Employee/EditEmpDetails/5    
            public ActionResult EditEmpDetails(int id)
            {
                EmpRepository EmpRepo = new EmpRepository();
                return View(EmpRepo.GetAllEmployees().Find(Emp => Emp.Empid == id));
            }
            // POST: Employee/EditEmpDetails/5    
            [HttpPost]
            public ActionResult EditEmpDetails(int id, EmpModel obj)
            {
                try
                {
                    EmpRepository EmpRepo = new EmpRepository();
                    EmpRepo.UpdateEmployee(obj);
                    return RedirectToAction("GetAllEmpDetails");
                }
                catch
                {
                    return View();
                }
            }
    // GET: Employee/DeleteEmp/5    
            public ActionResult DeleteEmp(int id)
            {
                try
                {
                    EmpRepository EmpRepo = new EmpRepository();
                    if (EmpRepo.DeleteEmployee(id))
                    {
                        ViewBag.AlertMsg = "Employee details deleted successfully";
    
                    }
                    return RedirectToAction("GetAllEmpDetails");
    
                }
                catch
                {
                    return View();
                }
            }
        }
    }

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

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

  • សូមធ្វើការ right click ទៅលើ ActionResult Method
  • បន្ទាប់មក click “Add View”
  • វានឹង popup ផ្ទាំងមួយមក

    • សូមធ្វើការរើសយក ដូចរូប
    • បន្ទាប់ពីចុច Add រួច នោះវានឹងធ្វើការ Generate code ដូចខាងក្រោម
      
      
      
      
      
      
      
      
      
      
      @model ASPMVCEmployee.Models.EmpModel
      @using (Html.BeginForm()) 
      {
          @Html.AntiForgeryToken()

      EmpModel

      @Html.ValidationSummary(true, “”, new { @class = “text-danger” })

      @Html.LabelFor(model => model.Empid, htmlAttributes: new { @class = “control-label col-md-2” })

      @Html.EditorFor(model => model.Empid, new { htmlAttributes = new { @class = “form-control” } }) @Html.ValidationMessageFor(model => model.Empid, “”, new { @class = “text-danger” })

      </div>

      @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = “control-label col-md-2” })

      @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = “form-control” } }) @Html.ValidationMessageFor(model => model.Name, “”, new { @class = “text-danger” })

      </div>

      @Html.LabelFor(model => model.City, htmlAttributes: new { @class = “control-label col-md-2” })

      @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = “form-control” } }) @Html.ValidationMessageFor(model => model.City, “”, new { @class = “text-danger” })

      </div>

      @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = “control-label col-md-2” })

      @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = “form-control” } }) @Html.ValidationMessageFor(model => model.Address, “”, new { @class = “text-danger” })

      </div>

      </div> </div> }

      @Html.ActionLink(“Back to List”, “GetAllEmpDetails”)

      @section Scripts { @Scripts.Render(“~/bundles/jqueryval”) }

      
      
      
      
    • បង្កើត Partial view ដើម្បី View employees
    • បន្ទាប់ពីចុច Add រួច នោះវានឹងធ្វើការ Generate code ដូចខាងក្រោម
@model IEnumerable<ASPMVCEmployee.Models.EmpModel>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Empid)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.City)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Address)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Empid)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.City)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Address)
        </td>
        <td>
            @Html.ActionLink("Edit", "EditEmpDetails", new { id=item.Empid  }) |
            @Html.ActionLink("Details", "Details", new { id = item.Empid }) |
            @Html.ActionLink("Delete", "DeleteEmp", new { id = item.Empid })        
</td>
    </tr>
}

</table>
  • បង្កើត Partial view ដើម្បី Update employees
  • បន្ទាប់ពីចុច Add រួច នោះវានឹងធ្វើការ Generate code ដូចខាងក្រោម
    @model ASPMVCEmployee.Models.EmpModel
    
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

    EmpModel

    @Html.ValidationSummary(true, “”, new { @class = “text-danger” })

    @Html.LabelFor(model => model.Empid, htmlAttributes: new { @class = “control-label col-md-2” })

    @Html.EditorFor(model => model.Empid, new { htmlAttributes = new { @class = “form-control” } }) @Html.ValidationMessageFor(model => model.Empid, “”, new { @class = “text-danger” })

    </div>

    @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = “control-label col-md-2” })

    @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = “form-control” } }) @Html.ValidationMessageFor(model => model.Name, “”, new { @class = “text-danger” })

    </div>

    @Html.LabelFor(model => model.City, htmlAttributes: new { @class = “control-label col-md-2” })

    @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = “form-control” } }) @Html.ValidationMessageFor(model => model.City, “”, new { @class = “text-danger” })

    </div>

    @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = “control-label col-md-2” })

    @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = “form-control” } }) @Html.ValidationMessageFor(model => model.Address, “”, new { @class = “text-danger” })

    </div>

    </div> </div> }

    @Html.ActionLink(“Back to List”, “GetAllEmpDetails”)

    @section Scripts { @Scripts.Render(“~/bundles/jqueryval”) }

    
    
    
    
    
    

11. ជំហានទី៨៖ ធ្វើការ Configure ActionLink ទៅលើ Edit និង delete records

  • នៅក្នុង​ file “GetAllEmpDetails.cshtml” សូមធ្វើការ edit link

12. ជំហានទី៩៖ Configure RouteConfig.cs ដើម្បី set default action

  • ក្នុង Folder “App_Start”
  • RouteConfig.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    
    namespace ASPMVCEmployee
    {
        public class RouteConfig
        {
            public static void RegisterRoutes(RouteCollection routes)
            {
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
                routes.MapRoute(
                    name: "Default",
                    url: "{controller}/{action}/{id}",
                    defaults: new { controller = "Employee", action = "AddEmployee", id = UrlParameter.Optional }
                );
            }
        }
    }

13. ជំហានទី១០៖ Run Application

ឥលូវនេះសូមធ្វើការ run the application

  • Add Employee
    • validation
    • Add record
  • List Employee
  • Edit Employee
    • Show in list again

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.