1.First of all create three different environment with i.Debug .To work with local environment ii.Staging Details…
Category: asp.net mvc
asp.net mvc
Add category like row with dynamic update with jQuery and ajax begin form
Model:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class CategoryViewModel { public long Id { get; set; } [Required] [StringLength(100, MinimumLength = 2, ErrorMessage = "Category Name cannot be longer than 100 characters and less than 2 characters")] [ValidateCategoryName(ErrorMessage = "Invalid name")] //Action result in controller which return Json object true while validation failed //[Remote("IsCategoryNameExists", "Category", "Settings", HttpMethod = "POST", ErrorMessage = "Catgory Name already exists")] public string Name { get; set; } [Required] public string Description { get; set; } //Edit Pupose //[ScaffoldColumn(false)] //public string PreviousName { get; set; } } |
and commonJqueryAjax
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
function commonJqueryAjax(myUrl, myData) { $.extend({ xResponse: function (url, data) { // local var var theResponse = null; // jQuery ajax $.ajax({ url: url, type: 'POST', data: JSON.stringify(data), async: false, contentType: 'application/json', success: function (respText) { theResponse = respText; }, error: function (jqXhr, textStatus, errorThrown) { alert('error ..Check log for details'); console.log(textStatus, errorThrown); var msg = ''; if (jqXhr.status === 0) { msg = 'Not connect.\n Verify Network.'; } else if (jqXhr.status == 404) { msg = 'Requested page not found. [404]'; } else if (jqXhr.status == 500) { msg = 'Internal Server Error [500].'; } else if (errorThrown === 'parsererror') { msg = 'Requested JSON parse failed.'; } else if (errorThrown === 'timeout') { msg = 'Time out error.'; } else if (errorThrown === 'abort') { msg = 'Ajax request aborted.'; } else { msg = 'Uncaught Error.\n' + jqXhr.responseText; } console.log(msg); } }); // Return the response text return theResponse; } }); // set ajax response in var var xData = $.xResponse(myUrl, myData); return xData; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 |
@model ERPSales.Web.Areas.Settings.ViewModels.CategoryViewModel @{ ViewBag.Title = "CategoryList"; //Layout = null; } <h2>CategoryList</h2> <button class="btn btn-primary" onclick="addCategory()">Add</button> <table class="table table-bordered" id="tbl"> <thead> <tr> <th> @Html.DisplayNameFor(model => model.Id) </th> <th> @Html.DisplayNameFor(model => model.Name) </th> <th> @Html.DisplayNameFor(model => model.Description) </th> <th> Action </th> </tr> </thead> <tbody> @foreach (var item in (List<ERPSales.Web.Areas.Settings.ViewModels.CategoryViewModel>)ViewBag.CategoryViewModels) { <tr> <td> @Html.DisplayFor(modelItem => item.Id) </td> <td> @Html.DisplayFor(modelItem => item.Name) </td> <td> @Html.DisplayFor(modelItem => item.Description) </td> <td> <button class="btn btn-success edit">Edit</button> <button class="btn btn-danger delete">Delete</button> </td> </tr> } </tbody> </table> <div id="result"> </div> <div> @{ AjaxOptions options = new AjaxOptions(); options.HttpMethod = "POST"; options.OnSuccess = "OnSuccessRequest"; options.OnFailure = "OnFailureRequest"; options.UpdateTargetId = "result"; options.InsertionMode = InsertionMode.Replace; } @using (Ajax.BeginForm("CreateCategory", "Category", new { area = "Settings" }, options, new { id = "formId" })) { <div class="modal fade" id="detailsModal"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <div class="form-horizontal"> <div class="form-group"> @Html.LabelFor(model => model.Id, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.TextBoxFor(model => model.Id) @Html.ValidationMessageFor(model => model.Id) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.TextBoxFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Description, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.TextBoxFor(model => model.Description) @Html.ValidationMessageFor(model => model.Description) </div> </div> </div> <div class="modal-footer"> <input type="submit" class="btn btn-success" value="Save" /> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> </div> } </div> <script> var currentRow; $(document).on('click', '.edit', function () { currentRow = $(this).closest('tr'); // currentRow.remove(); var id = $(this).parent().siblings(":first").text(); var url = '@Url.Action("CategoryById", "Category", new { area = "Settings" })'; var obj = {}; obj.id = id; var result = commonJqueryAjax(url, obj); $('#Id').val(result.Object.Id); $('#Name').val(result.Object.Name); $('#Description').val(result.Object.Description); addCategory(); }); $(document).on('click', '.delete', function () { // Do something on an existent or future .dynamicElement var id = $(this).parent().siblings(":first").text(); var url = '@Url.Action("DeleteCategory","Category",new{ area = "Settings" })'; var obj = {}; obj.id = id; var result = commonJqueryAjax(url, obj); //console.log(result); if (result.result == true) { alert('Deleted successfully'); $(this).closest('tr').remove(); } }); function OnSuccessRequest(result) { console.log(result); if (result.Errored == true) { alert(result.ErrorMessage); } else { //If edited remove the old row if (result.Edited == true) { alert('Edited Category'); currentRow.remove(); } else { alert('Added Category'); } var tr = '<tr>'; tr = tr + '<td>' + result.Object.Id + '</td>'; tr = tr + '<td>' + result.Object.Name + '</td>'; tr = tr + '<td>' + result.Object.Description + '</td>'; tr = tr + '<td>' + ' <button class="btn btn-success edit">Edit</button> <button class="btn btn-danger delete">Delete</button>' + '</td>'; tr = tr + '</tr>'; $('#tbl > tbody:first').prepend(tr); $('#detailsModal').modal('hide'); $('#formId')[0].reset(); } } function addCategory() { $('#detailsModal').modal({ show: true, backdrop: 'static' }); } function OnFailureRequest(jqXhr, textStatus, errorThrown) { alert('error ..Check log for details'); console.log(textStatus, errorThrown); var msg = ''; if (jqXhr.status === 0) { msg = 'Not connect.\n Verify Network.'; } else if (jqXhr.status == 404) { msg = 'Requested page not found. [404]'; } else if (jqXhr.status == 500) { msg = 'Internal Server Error [500].'; } else if (errorThrown === 'parsererror') { msg = 'Requested JSON parse failed.'; } else if (errorThrown === 'timeout') { msg = 'Time out error.'; } else if (errorThrown === 'abort') { msg = 'Ajax request aborted.'; } else { msg = 'Uncaught Error.\n' + jqXhr.responseText; } console.log(msg); } </script> |
and final updated version
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 |
@model ERPSales.Web.Areas.Settings.ViewModels.CategoryViewModel @{ ViewBag.Title = "CategoryList"; } <button class="btn btn-primary" onclick="addCategory()">Add</button> <table class="table table-bordered" id="tbl"> <thead> <tr> <th> @Html.DisplayNameFor(model => model.Id) </th> <th> @Html.DisplayNameFor(model => model.Name) </th> <th> @Html.DisplayNameFor(model => model.Description) </th> <th> Action </th> </tr> </thead> <tbody> @foreach (var item in (List<ERPSales.Web.Areas.Settings.ViewModels.CategoryViewModel>)ViewBag.CategoryViewModels) { <tr> <td> @Html.DisplayFor(modelItem => item.Id) </td> <td> @Html.DisplayFor(modelItem => item.Name) </td> <td> @Html.DisplayFor(modelItem => item.Description) </td> <td> <button class="btn btn-success edit">Edit</button> <button class="btn btn-danger delete">Delete</button> </td> </tr> } </tbody> </table> <div> @{ AjaxOptions options = new AjaxOptions(); options.HttpMethod = "POST"; options.OnSuccess = "OnSuccessRequest"; } @using (Ajax.BeginForm("CreateCategory", "Category", new { area = "Settings" }, options, new { id = "formId" })) { <div class="modal fade" id="detailsModal"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" onclick="closeModal()" aria-hidden="true"> × </button> <h4 class="modal-title" id="myModalLabel"> Category Add or Edit </h4> </div> <div class="modal-body"> <div class="form-horizontal"> <div class="form-group"> @Html.LabelFor(model => model.Id, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.TextBoxFor(model => model.Id, new { @class = "form-control", @disabled = "disabled" }) @Html.ValidationMessageFor(model => model.Id) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.TextBoxFor(model => model.Name, new { @class = "form-control"}) @Html.ValidationMessageFor(model => model.Name) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Description, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.TextAreaFor(model => model.Description, new { @class = "form-control"}) @Html.ValidationMessageFor(model => model.Description) </div> </div> </div> <div class="modal-footer"> <input type="submit" class="btn btn-success" value="Save" /> <button type="button" class="btn btn-info" onclick="closeModal()">Close</button> </div> </div> </div> </div> </div> } </div> <script> function closeModal() { //Hide the modal $('#detailsModal').modal('hide'); //Reset the form to previous state $('#formId')[0].reset(); } var currentEditedRow = false; //Edit // Do something on an existent or future .dynamicElement $(document).on('click', '.edit', function () { currentEditedRow = $(this).closest('tr'); // currentRow.remove() will be called after successfully edited the row //Get the form data and append it to form var id = $(this).parent().siblings(":first").text(); var url = '@Url.Action("CategoryById", "Category", new { area = "Settings" })'; var obj = {}; obj.id = id; var result = commonJqueryAjax(url, obj); console.log(result); $('#Id').val(result.Object.Id); $('#Name').val(result.Object.Name); $('#Description').val(result.Object.Description); addCategory(); }); //Delete $(document).on('click', '.delete', function () { var confrimDelete = confirm("Do you really want to delete?"); if (confrimDelete == true) { var id = $(this).parent().siblings(":first").text(); var url = '@Url.Action("DeleteCategory", "Category", new {area = "Settings"})'; var obj = {}; obj.id = id; var result = commonJqueryAjax(url, obj); if (result.result == true) { alert('Deleted successfully'); $(this).closest('tr').remove(); } } }); //Successful AJAX request will return _CategoryRow partial view and this method will prepend it to table id="tbl" function OnSuccessRequest(result) { console.log(result); if (currentEditedRow != false) { currentEditedRow.remove(); currentEditedRow = false; } var tr = result; $('#tbl > tbody:first').prepend(tr); } //POP up the modal function addCategory() { $('#detailsModal').modal({ show: true, backdrop: 'static' }); } //Failure request if any function OnFailureRequest(jqXhr, textStatus, errorThrown) { alert('error ..Check log for details'); console.log(textStatus, errorThrown); var msg = ''; if (jqXhr.status === 0) { msg = 'Not connect.\n Verify Network.'; } else if (jqXhr.status == 404) { msg = 'Requested page not found. [404]'; } else if (jqXhr.status == 500) { msg = 'Internal Server Error [500].'; } else if (errorThrown === 'parsererror') { msg = 'Requested JSON parse failed.'; } else if (errorThrown === 'timeout') { msg = 'Time out error.'; } else if (errorThrown === 'abort') { msg = 'Ajax request aborted.'; } else { msg = 'Uncaught Error.\n' + jqXhr.responseText; } console.log(msg); } </script> |
and controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using ERPSales.Core.Helpers; using ERPSales.Models.Settings; using ERPSales.Service.Settings.Interfaces; using ERPSales.Service.Settings.Services; using ERPSales.Web.Areas.Settings.ViewModels; using ERPSales.Web.Models; using Newtonsoft.Json; namespace ERPSales.Web.Areas.Settings.Controllers { public class CategoryController : Controller { private readonly ICategoryService _categoryService; public CategoryController(CategoryService categoryService) { _categoryService = categoryService; } public ActionResult CategoryList() { var categoryViewModel = new CategoryViewModel(); List<Category> categories = _categoryService.GetCategories(); var categoryViewModels = GenericMapper<Category, CategoryViewModel>.GetDestinationList(categories); //For showing category ViewBag.CategoryViewModels = categoryViewModels.OrderByDescending(x => x.Id).ToList(); return View(categoryViewModel); } [HttpPost] public PartialViewResult CreateCategory(CategoryViewModel categoryViewModel) { Category category = GenericMapper<CategoryViewModel, Category>.GetDestination(categoryViewModel); if (category.Id == 0) { //Add catgeory _categoryService.SaveCategory(category); categoryViewModel.Id = category.Id; } else { _categoryService.UpdateCategory(category); } return PartialView("~/Areas/Settings/Views/Category/Partial/_CategoryRow.cshtml", categoryViewModel); } [HttpPost] public JsonResult CategoryById(long id) { Category category = _categoryService.GetCategoryById(id); var categoryViewModel = GenericMapper<Category, CategoryViewModel>.GetDestination(category); var response = new Response<CategoryViewModel>(); response.Object = categoryViewModel; return Json(response, JsonRequestBehavior.AllowGet); } [HttpPost] public JsonResult DeleteCategory(CategoryViewModel categoryViewModel) { _categoryService.DeleteCategory(categoryViewModel.Id); return Json(new { result = true }, JsonRequestBehavior.AllowGet); } } } |
and Details…
Dynamic View Based On Database Table on MVC
You can easily generate a dynamic view based on table from this simple lines of Details…
I Unit of Work Pattern
KISS -Keep it simple stupid .A software principal to be followed in this blog post Details…
Asp.NET MVC 5 error login with ELMAH
Today i am showing you the coolest way to logging ASP.NET mvc login with ELMAH. Details…