Friday, August 9, 2019

Part 1 - How to Basic CRUD operations using Jquery ajax and modal popup in ASP.NET MVC4

Introduction

In this post, I am going to implement Basic CRUD (Create, Read, Update, Delete) operations using Jquery ajax and modal popup in ASP.NET MVC4 application.
I have split the entire application split into following 3 parts for making things more simple and understandable specially for beginners.

  • Part 1 : Perform read functionality of CRUD Operation.
  • Part 2 : Perform create and update functionality of CRUD Operation.
  • Part 3 : Perform delete functionality of CRUD Operation.

Step - 1 : Create New Project. Go to File > New > Project > Select asp.net MVC4 web application > Entry Application Name > Click OK > Select Basic Application > Select view engine Razor > OK

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create 3 tables for store Country, States and Contact information.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.

In this example, I have used 3 tables as below


Contacts

Countries
States

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Create a Folder

Here I have created a folder Named "ExtendedClass" in which we will create a class
Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New Folder > Rename Folder.

Step-6: Create a (partial) Class for extend 2 fileds CountryName and StateName. Here I have also added MetaData Class for Apply Validation on Contact Model.

Here I have created a (partial) class named "Contact"
Go to Solution Explorer > Right Click on the Folder > Add > Class > Enter class name > Add.

[N:B: I have changed namespace of the class "MVCPopupCRUD.ExtendedClass" to "MVCPopupCRUD" and make it partial class]
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Linq;
  5. using System.Web;
  6.  
  7. namespace MVCPopupCRUD
  8. {
  9. [MetadataType(typeof(ContactMetaData))]
  10. public partial class Contact
  11. {
  12. public string CountryName { get; set; }
  13. public string StateName { get; set; }
  14. }
  15.  
  16. public class ContactMetaData
  17. {
  18. [Required(ErrorMessage= "Contact Name required", AllowEmptyStrings = false)]
  19. [Display(Name="Contact Person")]
  20. public string ContactPerson { get; set; }
  21.  
  22. [Required(ErrorMessage="Contact No required", AllowEmptyStrings=false)]
  23. [Display(Name="Contact No")]
  24. public string ContactNo { get; set; }
  25.  
  26. [Required(ErrorMessage="Country required")]
  27. [Display(Name="Country")]
  28. public int CountryID { get; set; }
  29.  
  30. [Required(ErrorMessage="State required")]
  31. [Display(Name="State")]
  32. public int StateID { get; set; }
  33. }
  34. }

Step-7: Add a javascript file.

Go to Solution Explorer > Right Click on Scripts folder form Solution Explorer > Add new item...>Select JavaScript File> Enter file name (here "dotnetawesome.CRUDContacts.js") > Add.
Here we will write js code for open popup, create new contact, read, update and delete existing contact(s)

Step-8: Add a javascript function for show contact list . (read operation of CRUD)

  1. $(document).ready(function () {
  2.  
  3. //Populate Contact
  4. LoadContacts();
  5. });
  6. function LoadContacts() {
  7. $('#update_panel').html('Loading Data...');
  8.  
  9. $.ajax({
  10. url: '/home/GetContacts',
  11. type: 'GET',
  12. dataType: 'json',
  13. success: function (d) {
  14. if (d.length > 0) {
  15. var $data = $('<table></table>').addClass('table table-responsive table-striped');
  16. var header = "<thead><tr><th>Contact Person</th><th>Contact No</th><th>Country</th><th>State</th><th></th></tr></thead>";
  17. $data.append(header);
  18.  
  19. $.each(d, function (i, row) {
  20. var $row = $('<tr/>');
  21. $row.append($('<td/>').html(row.ContactPerson));
  22. $row.append($('<td/>').html(row.ContactNo));
  23. $row.append($('<td/>').html(row.CountryName));
  24. $row.append($('<td/>').html(row.StateName));
  25. $row.append($('<td/>').html("<a href='/home/Save/" + row.ContactID + "' class='popup'>Edit</a>&nbsp;|&nbsp;<a href='/home/Delete/" + row.ContactID + "' class='popup'>Delete</a>"));
  26. $data.append($row);
  27. });
  28.  
  29. $('#update_panel').html($data);
  30. }
  31. else {
  32. var $noData = $('<div/>').html('No Data Found!');
  33. $('#update_panel').html($noData);
  34. }
  35. },
  36. error: function () {
  37. alert('Error! Please try again.');
  38. }
  39. });
  40.  
  41. }

Step-9: Add a new Controller.

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name (Home) > Select Templete "empty MVC Controller"> Add.

Step-10: Add new action into your controller for get the view for show contact list.

Here I have used "Index" Action for show data. Please write this following code
  1. public ActionResult Index()
  2. {
  3. return View();
  4. }

Step-11: Add view for the Action & design.

Right Click on Action Method (here right click on index action) > Add View... > Enter View Name > Select View Engine (Razor) > Add. Complete View
  1. @{
  2. ViewBag.Title = "Contact List";
  3. }
  4.  
  5. <h2>Contact List</h2>
  6. @Html.ActionLink("Add New Contact","Save","Home",null,new{@style="font-size:22px;", @class="popup"})
  7.  
  8. <div id="update_panel">
  9.  
  10. </div>
  11. @* Add Jquery UI Css *@
  12. <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />
  13. <style>
  14. /*This is optional, I have added this for make looks good*/
  15. html, body,footer, #body {
  16. background-color:#fff;
  17. }
  18. .ui-widget-header {
  19. border: none !important;
  20. background: none !important;
  21. color: #222222;
  22. font-weight: bold;
  23. }
  24. .ui-state-default, .ui-state-hover {
  25. border: none !important;
  26. background: none !important;
  27. }
  28. .ui-dialog{
  29. webkit-box-shadow: 0 5px 15px rgba(0,0,0,.5);
  30. box-shadow: 0 5px 15px rgba(0,0,0,.5);
  31. }
  32. h2 {
  33. margin-top:0px;
  34. font-size:30px;
  35. }
  36. .success {
  37. color:green;
  38. }
  39. .failed {
  40. color:red;
  41. }
  42.  
  43. </style>
  44. @section Scripts{
  45. @*//Add Jquery UI JS*@
  46. <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  47. <script src="~/Scripts/dotnetawesome.CRUDContacts.js"></script>
  48. }
Optional: Here I have added Bootstrap css in the layout page for Responsive design.

Step-12: Add another action into your controller for return contact list as Json Data

Here I have used "GetContacts" Action for fetch data. Please write this following code
  1. public JsonResult GetContacts()
  2. {
  3. List<Contact> all = null;
  4.  
  5. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  6. {
  7. var contacts = (from a in dc.Contacts
  8. join b in dc.Countries on a.CountryID equals b.CountryID
  9. join c in dc.States on a.StateID equals c.StateID
  10. select new
  11. {
  12. a,
  13. b.CountryName,
  14. c.StateName
  15. });
  16. if (contacts != null)
  17. {
  18. all = new List<Contact>();
  19. foreach (var i in contacts)
  20. {
  21. Contact con = i.a;
  22. con.CountryName = i.CountryName;
  23. con.StateName = i.StateName;
  24. all.Add(con);
  25. }
  26. }
  27. }
  28.  
  29. return new JsonResult { Data = all, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
  30. }

Step-13: Run Application.

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...