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.
[N:B:Please Rebuild solution before add view.]
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.
- //Fetch Country from database
- private List<Country> GetCountry()
- {
- using (MyDatabaseEntities dc = new MyDatabaseEntities())
- {
- return dc.Countries.OrderBy(a => a.CountryName).ToList();
- }
- }
Step-2: Write function for fetch states from database.
Here I have written the below function "GetState" into "Home" Controller.
- //Fetch State from database
- private List<State> GetState(int countryID)
- {
- using (MyDatabaseEntities dc = new MyDatabaseEntities())
- {
- return dc.States.Where(a => a.CountryID.Equals(countryID)).OrderBy(a => a.StateName).ToList();
- }
- }
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.
- //return states as json data
- public JsonResult GetStateList(int countryID)
- {
- using (MyDatabaseEntities dc = new MyDatabaseEntities())
- {
- return new JsonResult { Data = GetState(countryID), JsonRequestBehavior = JsonRequestBehavior.AllowGet };
- }
- }
Step-4: Write function for fetch contact data from database.
Here I have written the below function "GetContact" into "Home" Controller.
- //Get contact by ID
- public Contact GetContact(int contactID)
- {
- Contact contact = null;
- using (MyDatabaseEntities dc = new MyDatabaseEntities())
- {
- var v = (from a in dc.Contacts
- join b in dc.Countries on a.CountryID equals b.CountryID
- join c in dc.States on a.StateID equals c.StateID
- where a.ContactID.Equals(contactID)
- select new
- {
- a,
- b.CountryName,
- c.StateName
- }).FirstOrDefault();
- if (v != null)
- {
- contact = v.a;
- contact.CountryName = v.CountryName;
- contact.StateName = v.StateName;
- }
- return contact;
- }
- }
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
- public ActionResult Save(int id = 0)
- {
- List<Country> Country = GetCountry();
- List<State> States = new List<State>();
- if (id > 0)
- {
- var c = GetContact(id);
- if (c != null)
- {
- ViewBag.Countries = new SelectList(Country, "CountryID", "CountryName", c.CountryID);
- ViewBag.States = new SelectList(GetState(c.CountryID), "StateID", "StateName", c.StateID);
- }
- else
- {
- return HttpNotFound();
- }
- return PartialView("Save", c);
- }
- else
- {
- ViewBag.Countries = new SelectList(Country, "CountryID", "CountryName");
- ViewBag.States = new SelectList(States, "StateID", "StateName");
- return PartialView("Save");
- }
- }
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.]
- @model MVCPopupCRUD.Contact
- <h2>Save Contact</h2>
- @using (Html.BeginForm("Save","Home", FormMethod.Post, new{role = "form", id = "saveForm"}))
- {
- @*here role = "form" for bootstrap design (optional) *@
- @Html.ValidationSummary(true)
- @Html.AntiForgeryToken()
- <div class="form-group">
- @Html.HiddenFor(model=>model.ContactID)
- @Html.LabelFor(model=> model.ContactPerson)
- @Html.TextBoxFor(model => model.ContactPerson, new { @class="form-control"})
- </div>
- <div class="form-group">
- @Html.LabelFor(model=> model.ContactNo)
- @Html.TextBoxFor(model => model.ContactNo, new { @class="form-control"})
- </div>
- <div class="form-group">
- @Html.LabelFor(model=> model.CountryID)
- @Html.DropDownListFor(model=>model.CountryID, ViewBag.Countries as SelectList,"Select Country",new{@class = "form-control"})
- </div>
- <div class="form-group">
- @Html.LabelFor(model=> model.StateID)
- @Html.DropDownListFor(model=>model.StateID, ViewBag.States as SelectList,"Select State",new{@class = "form-control"})
- </div>
- <button type="submit" class="btn btn-default">Submit</button>
- @Html.ActionLink("Back To List","Index", null, new {@style="margin-left:50px; font-weight:bold;"})
- <div id="msg"></div>
- }
Step-7: Add an another action for POST method for Save contact to the database.
Please write below code
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult Save(Contact c)
- {
- string message = "";
- bool status = false;
- if (ModelState.IsValid)
- {
- using (MyDatabaseEntities dc = new MyDatabaseEntities())
- {
- if (c.ContactID > 0)
- {
- var v = dc.Contacts.Where(a => a.ContactID.Equals(c.ContactID)).FirstOrDefault();
- if (v != null)
- {
- v.ContactPerson = c.ContactPerson;
- v.ContactNo = c.ContactNo;
- v.CountryID = c.CountryID;
- v.StateID = c.StateID;
- }
- else
- {
- return HttpNotFound();
- }
- }
- else
- {
- dc.Contacts.Add(c);
- }
- dc.SaveChanges();
- status = true;
- message = "Successfully Saved.";
- }
- }
- else
- {
- message = "Error! Please try again.";
- }
- return new JsonResult { Data = new { status = status, message = message} };
- }
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 codeAdd following jquery code inside $(document).ready for bind with elements (those have "popup" class) click event
- //open popup
- function OpenPopup(Page) {
- var $pageContent = $('<div/>');
- $pageContent.load(Page);
- $dialog = $('<div class="popupWindow" style="overflow:hidden"></div>')
- .html($pageContent)
- .dialog({
- draggable: false,
- autoOpen: false,
- resizable: false,
- model: true,
- height: 600,
- width: 600,
- close: function () {
- $dialog.dialog('destroy').remove();
- }
- })
- $dialog.dialog('open');
- }
- //Open popup
- $('body').on("click", "a.popup", function (e) {
- e.preventDefault();
- var page = $(this).attr('href');
- OpenPopup(page);
- });
Step-9: Add an another javascript function (LoadStates) for load states of the selected country (cascade dropdown)
Add following jquery code inside $(document).ready for bind country dropdown change event for cascade dropdown
- //Casecade dropdown - Populate states of selected country
- function LoadStates(countryID) {
- var $state = $('#StateID');
- $state.empty();
- $state.append($('<option></option>').val('').html('Please Wait...'));
- if (countryID == null || countryID == "") {
- $state.empty();
- $state.append($('<option></option>').val('').html('Select State'));
- return;
- }
- $.ajax({
- url: '/home/GetStateList',
- type: 'GET',
- data: { 'countryID': countryID },
- dataType: 'json',
- success: function (d) {
- $state.empty();
- $state.append($('<option></option>').val('').html('Select State'));
- $.each(d, function (i, val) {
- $state.append($('<option></option>').val(val.StateID).html(val.StateName));
- });
- },
- error: function () {
- }
- });
- }
- $('body').on('change', '#CountryID', function () {
- var countryID = $(this).val();
- LoadStates(countryID);
- });
Step-10: Add another javascript function (SaveContacts) for Save contact (create and update) to the database
Please write this following code
- //Save Contact
- function SaveContacts() {
- //Validation
- if ($('#ContactPerson').val().trim() == '' ||
- $('#ContactNo').val().trim() == '' ||
- $('#CountryID').val().trim() == '' ||
- $('#StateID').val().trim() == '') {
- $('#msg').html('<div class="failed">All fields are required.</div>');
- return false;
- }
- var contact = {
- ContactID: $('#ContactID').val() == '' ? '0' : $('#ContactID').val(),
- ContactPerson: $('#ContactPerson').val().trim(),
- ContactNo: $('#ContactNo').val().trim(),
- CountryID: $('#CountryID').val().trim(),
- StateID: $('#StateID').val().trim()
- };
- //Add validation token
- contact.__RequestVerificationToken = $('input[name=__RequestVerificationToken]').val();
- //Save Contact
- $.ajax({
- url: '/home/Save',
- type: 'POST',
- data: contact,
- dataType: 'json',
- success: function (data) {
- alert(data.message);
- if (data.status) {
- $('#ContactID').val('');
- $('#ContactPerson').val('');
- $('#ContactNo').val('');
- $('#CountryID').val('');
- $('#StateID').val('');
- LoadContacts();
- $dialog.dialog('close');
- }
- },
- error: function () {
- $('#msg').html('<div class="failed">Error! Please try again.</div>');
- }
- });
- }
- //Save Contacts
- $("body").on('submit', '#saveForm', function (e) {
- e.preventDefault();
- SaveContacts();
- });
No comments:
Post a Comment