Introduction
Hi guys. In this article I am going to explain to you how to add a subcategories list under the main category & display them into the table on the same view, then submit to the controller in MVC using jquery.
Like this:
Here I first add Jewelry Name (which is a category). If I check on the Have SubCategory? checkbox then subcategory panel displays for adding subcategories one by one under this category.
And on click of the plus button, a subcategory is added to the below table immediately and then we submit this data to the controller for saving into the database.
For this process, I am using jquery so my page does not need to be refreshed and data stores locally while being added, after submission of its stores into the database.
Let's do it.
First create AddEditController.cs to your mvc application then create AddEditJewelry() action method:
- public ActionResult AddEditJewelry(int ? id) {
- JewelryDto model = new JewelryDto();
- if (id.HasValue) {
-
- model.subcategories = xyz.ToList();
- } else {
- model = new JewelryDto();
- }
- return View(model);
- }
Now, add AddEditJewelry.cshtml view
- @model ALS.Services.JewelryDto
- <div id="frm-create-edit-Jewelry" class="cmxform">
- @using (Html.BeginForm())
- {
- @Html.AntiForgeryToken()
-
-
- <div id="validation-summary" style="display:none" class="alert alert-danger alert-dismissable"></div>
- <div class="modal-body form-horizontal">
- <div class="form-group">
- @Html.HiddenFor(model => model.JewelryId)
- @Html.LabelFor(model => model.Name, new { @class = "col-lg-3 col-sm-3 control-label" })
-
- <div class="col-lg-9 col-sm-9">
- @Html.TextBoxFor(model => model.Name, true, null, new { @class = "form-control ", @maxlength = 100, @onchange = "CheckJewelryName(this)" })
- </div>
- </div>
- <div class="form-group">
- <div class="col-lg-3 col-sm-3"></div>
- <div class="col-lg-9 col-sm-9" id="divhavesubcat" style="display:@(Model.JewelryId > 0?"block":"none")">
- <div class="checkbox icheck">
- @Html.CheckBoxFor(model => model.IsSubCat, new { @class = "form-checkbox" })
-
- <label id="lblehavesub"> Have SubCategory?</label>
- </div>
- </div>
- </div>
-
- @if (Model.JewelryId > 0 && Model.subcategories != null)
- {
-
- <table id="grdsubcatupdate" class="table table-bordered table-striped table-responsive-md">
- <thead>
- <tr>
- <td>Name</td>
- <td>Action</td>
- </tr>
- </thead>
- <tbody>
- @foreach (JewelrySubCategory item in Model.subcategories)
- {
-
- <tr>
- <td>@item.Name </td>
- <td>
- <a data-toggle="modal" data-target="#modal-delete-subJewelry" href="@Url.Action("DeleteSubCategory", "Jewelry", new { id = item.JsubId })">
- <i class="fa fa-trash-o"></i>
- </a>
- </td>
- </tr>
- }
-
-
- </tbody>
- </table>
- }
-
-
- <div id="divsubcat" style="display:none">
- <div class="form-group">
- <div class="col-lg-9 col-sm-9">
- @Html.HiddenFor(model => model.SubJId)
- @Html.LabelFor(model => model.SubcatName, new { @class = "col-lg-3 col-sm-3 control-label" })
- @Html.TextBoxFor(model => model.SubcatName, true, null, new { @class = "form-control ", @maxlength = 100, @onchange = "CheckSubJName(this)" })
-
- </div>
- <div class="col-lg-3 col-sm-3" style="margin-top: 25px;">
- <a class="btn btn-primary" id="btnAddCollection">
- <i class="fa fa-plus"></i>
- </a>
- </div>
- </div>
- <table id="grdsubcatsave" class="table table-bordered table-striped table-responsive-md" style="display:none">
- <thead>
- <tr>
- <td>Name</td>
- <td>Action</td>
- </tr>
- </thead>
- <tbody></tbody>
- </table>
- </div>
- </div>
- <div class="modal-footer">
- <button class="btn btn-success" id="btn-submit" type="button">
- Submit
- </button>
- </div>
- }
-
- </div>
The HideShow() function displays the subcategory panel on click of the Have Subcategory? checkbox.
- function HideShow() {
-
- var count = 0;
- $('#IsSubCat').on("change", function () {
- if (count == 1) {
- $("#IsSubCat").prop("checked", true);
- $('#divsubcat').show();
- count = 0;
- }
- else {
- $("#IsSubCat").prop("checked", false);
- $('#divsubcat').hide();
- count++;
- }
- })
-
- }
On click of the 'btnAddCollection' button, this function checks that the subcategory you added already exists in array collection or not. If it exists then it shows an error message otherwise it adds that into the displayed table and pushes that category into array, 'CollectionList'.
- CollectionList = [];
- $('#btnAddCollection').on('click', function() {
- debugger;
- if (isSubJNameExist) {} else {
- $('#validation-summary').hide();
- $('#validation-summary').html('');
- isSubJNameExist = false;
- var collection = $('#SubcatName').val();
- var Name = $('#Name').val();
- if (collection == '' || collection == 'undefined' || collection == undefined) {
- showerror('Sub category Name is requierd. ')
- } else if (Name == '' || Name == 'undefined' || Name == undefined) {
- showerror('Jewelry Name is requierd. ')
- } else {
- removeerror();
- $('#grdsubcatsave').show();
- var isExist = false;
- $.each(CollectionList, function(i, value) {
- if (value.ColletionName === collection) {
- isExist = true;
- } else {
- isExist = false;
- }
- });
- if (isExist) {
- showerror("Already Exist in current collection.")
- } else {
- removeerror();
- var row = "<tr id='" + collection + "'><td>" + collection + "</td> <td> <a href='#'> <i class='fa fa-trash-o'></i></a> </td>";
- $('#grdsubcatsave>tbody').append(row);
- var collDto = {
- ColletionName: collection
- };
- CollectionList.push(collDto);
- $('#SubcatName').val('')
- }
- }
- }
- });
This function checks the subcategory name from the database. If it exists in the database then it shows an error message, otherwise it removes the error.
- function CheckSubJName(reff) {
- var name = $(reff).val();
- if (name != "" && name != "undefined") {
- $.ajax({
- type: "POST",
- contentType: "application/json; charset=utf-8",
- url: domain + "admin/jewelry/CheckSubJNameExist",
- data: '{Name:' + JSON.stringify(name) + '}',
- dataType: "json",
-
- success: function(result) {
- debugger;
- if (result === "Exist") {
- isSubJNameExist = true;
- showerror('Sub Jewelry Name Already Exist With us.')
- } else {
- isSubJNameExist = false;
- removeerror();
- }
- },
- error: function ajaxError(result) {
- $('#validation-summary').html('Something Went Wrong.');
- }
- });
- }
- }
Now, on click of save button, call an Ajax for saving this collection into the database.
- $('#btn-submit').on('click', function () {
-
- if ($('#validation-summary').hasClass("error")) {
- }
- else {
- removeerror();
- AddCollection();
- }
-
- })
- function removeerror() {
- $('#validation-summary').hide();
- $('#validation-summary').html('');
- $('#validation-summary').removeAttr("class");
- }
And now from here, we can add / update collection list by Ajax call.
- function AddCollection() {
- if (CollectionList.length > 0) {
- debugger;
- var jname = $('#Name').val();
- var jid = $('#JewelryId').val();
- var model = JSON.stringify(CollectionList)
- $.ajax({
- type: "POST",
- url: domain + "admin/jewelry/AddEditJewelry",
- contentType: "application/json;charset=utf-8",
- data: JSON.stringify({
- data1: model,
- Name: jname,
- JewelryId: jid
- }),
- dataType: "json",
- success: function(msg) {
- if (msg == "Success") {
- window.location.href = domain + "admin/home/index";
- } else {
- alert("Something went wrong");
- }
- },
- error: function(xmlhttprequest, textstatus, errorthrown) {}
- });
- } else {
- var jname = $('#Name').val();
- var jid = $('#JewelryId').val();
- $.ajax({
- type: "POST",
- url: domain + "admin/jewelry/AddEditJewelry",
- contentType: "application/json;charset=utf-8",
- data: JSON.stringify({
- Name: jname,
- JewelryId: jid
- }),
- dataType: "json",
- success: function(msg) {
- if (msg == "Success") {
- window.location.href = domain + "admin/home/index";
- } else {
- alert("Something went wrong");
- }
- },
- error: function(xmlhttprequest, textstatus, errorthrown) {}
- });
- }
- }
You can see the final jewelry.js here:
- $(document).ready(function() {
- var CollectionList = [];
- HideShow();
- addSubcategories();
-
- function HideShow() {
- var count = 0;
- $('#IsSubCat').on("change", function() {
- if (count == 1) {
- $("#IsSubCat").prop("checked", true);
- $('#divsubcat').show();
- count = 0;
- } else {
- $("#IsSubCat").prop("checked", false);
- $('#divsubcat').hide();
- count++;
- }
- })
- }
-
- function addSubcategories() {
- CollectionList = [];
- $('#btnAddCollection').on('click', function() {
- debugger;
- if (isSubJNameExist) {} else {
- $('#validation-summary').hide();
- $('#validation-summary').html('');
- isSubJNameExist = false;
- var collection = $('#SubcatName').val();
- var Name = $('#Name').val();
- if (collection == '' || collection == 'undefined' || collection == undefined) {
- showerror('Sub category Name is requierd. ')
- } else if (Name == '' || Name == 'undefined' || Name == undefined) {
- showerror('Jewelry Name is requierd. ')
- } else {
- removeerror();
- $('#grdsubcatsave').show();
- var isExist = false;
- $.each(CollectionList, function(i, value) {
- if (value.ColletionName === collection) {
- isExist = true;
- } else {
- isExist = false;
- }
- });
- if (isExist) {
- showerror("Already Exist in current collection.")
- } else {
- removeerror();
- var row = "<tr id='" + collection + "'><td>" + collection + "</td> <td> <a href='#'> <i class='fa fa-trash-o'></i></a> </td>";
- $('#grdsubcatsave>tbody').append(row);
- var collDto = {
- ColletionName: collection
- };
- CollectionList.push(collDto);
- $('#SubcatName').val('')
- }
- }
- }
- });
- $('#btn-submit').on('click', function() {
- if ($('#validation-summary').hasClass("error")) {} else {
- removeerror();
- AddCollection();
- }
- })
-
- function AddCollection() {
- if (CollectionList.length > 0) {
- debugger;
- var jname = $('#Name').val();
- var jid = $('#JewelryId').val();
- var model = JSON.stringify(CollectionList)
- $.ajax({
- type: "POST",
- url: domain + "admin/jewelry/AddEditJewelry",
- contentType: "application/json;charset=utf-8",
- data: JSON.stringify({
- data1: model,
- Name: jname,
- JewelryId: jid
- }),
- dataType: "json",
- success: function(msg) {
- if (msg == "Success") {
- window.location.href = domain + "admin/home/index";
- } else {
- alert("Something went wrong");
- }
- },
- error: function(xmlhttprequest, textstatus, errorthrown) {}
- });
- } else {
- var jname = $('#Name').val();
- var jid = $('#JewelryId').val();
- $.ajax({
- type: "POST",
- url: domain + "admin/jewelry/AddEditJewelry",
- contentType: "application/json;charset=utf-8",
- data: JSON.stringify({
- Name: jname,
- JewelryId: jid
- }),
- dataType: "json",
- success: function(msg) {
- if (msg == "Success") {
- window.location.href = domain + "admin/home/index";
- } else {
- alert("Something went wrong");
- }
- },
- error: function(xmlhttprequest, textstatus, errorthrown) {}
- });
- }
- }
- }
- })
Now on the HTTP post on AddEditJewelry.cs controller we get collection data into variables with names like eg.data1, Name, and JewelryId parameters. Here I first get the jewelry category by id and hold it into the model if it's null, which means no entry into the DB. So we initialize var cls = new Jewelry(); memory and then save it or update it into the database on the base of jewelry id.
- [HttpPost]
- public ActionResult AddEditJewelry(string data1, string Name, string JewelryId) {
- try {
- var msg = "";
- if (!String.IsNullOrEmpty(Name)) {
- var jid = Convert.ToDecimal(JewelryId);
- Jewelry cls = collectionService.GetJewelryById(jid);
- if (cls == null) {
- cls = new Jewelry();
- }
- cls.JewelryId = Convert.ToDecimal(JewelryId);
- cls.Name = Name;
- cls.Photo = "";
- collectionService.SaveJewelry(cls);
- if (data1 != null && data1 != "undefined" && cls.JewelryId > 0) {
- List < JewelrySubCategory > list = new List < JewelrySubCategory > ();
- List < JsubName > subcats = JsonConvert.DeserializeObject < List < JsubName >> (data1);
- foreach(JsubName item in subcats) {
- JewelrySubCategory subcatmodel = new JewelrySubCategory();
- subcatmodel.JewelryId = cls.JewelryId;
- subcatmodel.Name = item.ColletionName;
- subcatmodel.Photo = "";
- list.Add(subcatmodel);
- }
- collectionService.SaveSubCategories(list);
- }
- msg = "Jewelry has been saved successfully.";
- return Json("Success", JsonRequestBehavior.AllowGet);
- } else {
- msg = "There is some errors, Please re-check all the details.";
- return Json("Fail", JsonRequestBehavior.AllowGet);
- }
- } catch (Exception ex) {}
- return null;
- }
Make a class for deserialization of subcategory name, and make sure the CollectionName Property and class property name should be the same so that we can serialize it easily.
- var collDto = { ColletionName: collection };
- CollectionList.push(collDto);
- public class JsubName
- {
- public string ColletionName { get; set; }
- }
Conclusion
So finally, we get the output displayed like it is at the top of the article.