Friday, August 9, 2019

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

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 2 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: Write function for fetch countries from database.

Here I have written the below function "GetCountry" into "Home" Controller. 
  1. //Fetch Country from database
  2. private List<Country> GetCountry()
  3. {
  4. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  5. {
  6. return dc.Countries.OrderBy(a => a.CountryName).ToList();
  7. }
  8. }

Step-2: Write function for fetch states from database.

Here I have written the below function "GetState" into "Home" Controller. 
  1. //Fetch State from database
  2. private List<State> GetState(int countryID)
  3. {
  4. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  5. {
  6. return dc.States.Where(a => a.CountryID.Equals(countryID)).OrderBy(a => a.StateName).ToList();
  7. }
  8. }

Step-3: Write function for return state list of selected country in json format, which we will use for cascade dropdown.

Here I have written the below function "GetStateList" into "Home" Controller. 
  1. //return states as json data
  2. public JsonResult GetStateList(int countryID)
  3. {
  4. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  5. {
  6. return new JsonResult { Data = GetState(countryID), JsonRequestBehavior = JsonRequestBehavior.AllowGet };
  7. }
  8. }

Step-4: Write function for fetch contact data from database.

Here I have written the below function "GetContact" into "Home" Controller. 
  1. //Get contact by ID
  2. public Contact GetContact(int contactID)
  3. {
  4. Contact contact = null;
  5. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  6. {
  7. var v = (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. where a.ContactID.Equals(contactID)
  11. select new
  12. {
  13. a,
  14. b.CountryName,
  15. c.StateName
  16. }).FirstOrDefault();
  17. if (v != null)
  18. {
  19. contact = v.a;
  20. contact.CountryName = v.CountryName;
  21. contact.StateName = v.StateName;
  22. }
  23. return contact;
  24. }
  25. }

Step-5: Add new action into your controller for get view for Save (Add and Edit) contact.

Here I have used "Save" Action. Please write below code
  1. public ActionResult Save(int id = 0)
  2. {
  3. List<Country> Country = GetCountry();
  4. List<State> States = new List<State>();
  5.  
  6. if (id > 0)
  7. {
  8. var c = GetContact(id);
  9. if (c != null)
  10. {
  11. ViewBag.Countries = new SelectList(Country, "CountryID", "CountryName", c.CountryID);
  12. ViewBag.States = new SelectList(GetState(c.CountryID), "StateID", "StateName", c.StateID);
  13. }
  14. else
  15. {
  16. return HttpNotFound();
  17. }
  18. return PartialView("Save", c);
  19. }
  20. else
  21. {
  22. ViewBag.Countries = new SelectList(Country, "CountryID", "CountryName");
  23. ViewBag.States = new SelectList(States, "StateID", "StateName");
  24. return PartialView("Save");
  25. }
  26. }

Step-6: Add partial view for the "Save" Action & design.

Right Click on Shared folder (under Views) > Add > View... > Enter View Name > Select View Engine (Razor) > Check "Create a strong-typed view" > Select your model class > Check "Create as a Partial View" > Add. 
[N:B:Please Rebuild solution before add view.] 
  1. @model MVCPopupCRUD.Contact
  2. <h2>Save Contact</h2>
  3. @using (Html.BeginForm("Save","Home", FormMethod.Post, new{role = "form", id = "saveForm"}))
  4. {
  5. @*here role = "form" for bootstrap design (optional) *@
  6. @Html.ValidationSummary(true)
  7. @Html.AntiForgeryToken()
  8.  
  9. <div class="form-group">
  10. @Html.HiddenFor(model=>model.ContactID)
  11. @Html.LabelFor(model=> model.ContactPerson)
  12. @Html.TextBoxFor(model => model.ContactPerson, new { @class="form-control"})
  13. </div>
  14. <div class="form-group">
  15. @Html.LabelFor(model=> model.ContactNo)
  16. @Html.TextBoxFor(model => model.ContactNo, new { @class="form-control"})
  17. </div>
  18. <div class="form-group">
  19. @Html.LabelFor(model=> model.CountryID)
  20. @Html.DropDownListFor(model=>model.CountryID, ViewBag.Countries as SelectList,"Select Country",new{@class = "form-control"})
  21. </div>
  22. <div class="form-group">
  23. @Html.LabelFor(model=> model.StateID)
  24. @Html.DropDownListFor(model=>model.StateID, ViewBag.States as SelectList,"Select State",new{@class = "form-control"})
  25. </div>
  26. <button type="submit" class="btn btn-default">Submit</button>
  27. @Html.ActionLink("Back To List","Index", null, new {@style="margin-left:50px; font-weight:bold;"})
  28. <div id="msg"></div>
  29. }

Step-7: Add an another action for POST method for Save contact to the database.

Please write below code
  1. [HttpPost]
  2. [ValidateAntiForgeryToken]
  3. public ActionResult Save(Contact c)
  4. {
  5. string message = "";
  6. bool status = false;
  7. if (ModelState.IsValid)
  8. {
  9. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  10. {
  11. if (c.ContactID > 0)
  12. {
  13. var v = dc.Contacts.Where(a => a.ContactID.Equals(c.ContactID)).FirstOrDefault();
  14. if (v != null)
  15. {
  16. v.ContactPerson = c.ContactPerson;
  17. v.ContactNo = c.ContactNo;
  18. v.CountryID = c.CountryID;
  19. v.StateID = c.StateID;
  20. }
  21. else
  22. {
  23. return HttpNotFound();
  24. }
  25. }
  26. else
  27. {
  28. dc.Contacts.Add(c);
  29. }
  30. dc.SaveChanges();
  31. status = true;
  32. message = "Successfully Saved.";
  33. }
  34. }
  35. else
  36. {
  37. message = "Error! Please try again.";
  38. }
  39.  
  40. return new JsonResult { Data = new { status = status, message = message} };
  41. }

Step-8: Add a javascript function (here "OpenPopup") for open popup.

Open javascript file (we have created in part 1 step 7, here "dotnetawesome.CRUDContacts.js") and write following code 
  1. //open popup
  2. function OpenPopup(Page) {
  3. var $pageContent = $('<div/>');
  4. $pageContent.load(Page);
  5. $dialog = $('<div class="popupWindow" style="overflow:hidden"></div>')
  6. .html($pageContent)
  7. .dialog({
  8. draggable: false,
  9. autoOpen: false,
  10. resizable: false,
  11. model: true,
  12. height: 600,
  13. width: 600,
  14. close: function () {
  15. $dialog.dialog('destroy').remove();
  16. }
  17. })
  18. $dialog.dialog('open');
  19. }
Add following jquery code inside $(document).ready for bind with elements (those have "popup" class) click event
  1. //Open popup
  2. $('body').on("click", "a.popup", function (e) {
  3. e.preventDefault();
  4. var page = $(this).attr('href');
  5. OpenPopup(page);
  6. });

Step-9: Add an another javascript function (LoadStates) for load states of the selected country (cascade dropdown)

  1. //Casecade dropdown - Populate states of selected country
  2. function LoadStates(countryID) {
  3. var $state = $('#StateID');
  4. $state.empty();
  5. $state.append($('<option></option>').val('').html('Please Wait...'));
  6. if (countryID == null || countryID == "") {
  7. $state.empty();
  8. $state.append($('<option></option>').val('').html('Select State'));
  9. return;
  10. }
  11.  
  12. $.ajax({
  13. url: '/home/GetStateList',
  14. type: 'GET',
  15. data: { 'countryID': countryID },
  16. dataType: 'json',
  17. success: function (d) {
  18. $state.empty();
  19. $state.append($('<option></option>').val('').html('Select State'));
  20. $.each(d, function (i, val) {
  21. $state.append($('<option></option>').val(val.StateID).html(val.StateName));
  22. });
  23. },
  24. error: function () {
  25.  
  26. }
  27. });
  28.  
  29. }
Add following jquery code inside $(document).ready for bind country dropdown change event for cascade dropdown
  1. $('body').on('change', '#CountryID', function () {
  2. var countryID = $(this).val();
  3. LoadStates(countryID);
  4. });

Step-10: Add another javascript function (SaveContacts) for Save contact (create and update) to the database

Please write this following code
  1. //Save Contact
  2. function SaveContacts() {
  3. //Validation
  4. if ($('#ContactPerson').val().trim() == '' ||
  5. $('#ContactNo').val().trim() == '' ||
  6. $('#CountryID').val().trim() == '' ||
  7. $('#StateID').val().trim() == '') {
  8. $('#msg').html('<div class="failed">All fields are required.</div>');
  9. return false;
  10. }
  11.  
  12. var contact = {
  13. ContactID: $('#ContactID').val() == '' ? '0' : $('#ContactID').val(),
  14. ContactPerson: $('#ContactPerson').val().trim(),
  15. ContactNo: $('#ContactNo').val().trim(),
  16. CountryID: $('#CountryID').val().trim(),
  17. StateID: $('#StateID').val().trim()
  18. };
  19. //Add validation token
  20. contact.__RequestVerificationToken = $('input[name=__RequestVerificationToken]').val();
  21. //Save Contact
  22. $.ajax({
  23. url: '/home/Save',
  24. type: 'POST',
  25. data: contact,
  26. dataType: 'json',
  27. success: function (data) {
  28. alert(data.message);
  29. if (data.status) {
  30. $('#ContactID').val('');
  31. $('#ContactPerson').val('');
  32. $('#ContactNo').val('');
  33. $('#CountryID').val('');
  34. $('#StateID').val('');
  35. LoadContacts();
  36. $dialog.dialog('close');
  37. }
  38. },
  39. error: function () {
  40. $('#msg').html('<div class="failed">Error! Please try again.</div>');
  41. }
  42. });
  43. }

  1. //Save Contacts
  2. $("body").on('submit', '#saveForm', function (e) {
  3. e.preventDefault();
  4. SaveContacts();
  5. });

Step-11: 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 { ...