Introduction
This article demonstrates how to create and use an insert, update and delete recored using asp.net MVC with C# technology. In this article first of all I'll explain the mvc and also how to make an ajax call in mvc with the server side call, then I'll explain Entity framework and how to make a validation in your project using jquery and javascript.
C-Create-POST
R - Read - GET
U - Update - PUT
D - Delete – DELETE
What is MVC?
The Model-View-Controller (MVC) is an architectural pattern that separates an application into three main logical components: the Model, the View, and the Controller. Each of these components is built to handle specific development aspects of an application. MVC is one of the most frequently used industry-standard web development frameworks to create scalable and extensible projects.
- Model - The Model is the part of the application that handles the logic for the application data.Often model objects retrieve data (and store data) from a database.
- View is the parts of the application that handles the display of the data. Most often the views are created from the model data.
- Controller is the part of the application that handles user interaction.Typically controllers read data from a view, control user input, and send input data to the model.
What is Entity Framework?
- Object/Relational Mapping (ORM) framework
- Work with database as domain-specific objects
- Retrieve and manipulate data as strongly typed objects
What is AJAX Call?
Your method returns JSON result. This is MVC specific and you cannot use it in a webforms application if you want to call methods in the code behind.
- public JsonResult AddToCart(int PID)
- {
- var result = new jsonMessage();
- try
- {
-
- Mst_Product _Mst_Product = context.Mst_Product.Where(t => t.PID == PID).FirstOrDefault();
-
-
- Cart _Cart = new Cart();
- _Cart.PID = PID;
- _Cart.Quantity = 1;
- _Cart.DateTime = System.DateTime.Now;
- _Cart.TotalPrice = Convert.ToDouble(_Mst_Product.Price);
-
- context.Carts.Add(_Cart);
- result.Message = "your product has been Added in to cart..";
- result.Status = true;
-
- context.SaveChanges();
-
-
- }
- catch (Exception ex)
- {
- ErrorLogers.ErrorLog(ex);
- result.Message = "We are unable to process your request at this time. Please try again later.";
- result.Status = false;
- }
- return Json(result, JsonRequestBehavior.AllowGet);
- }
- $.ajax({
- url: '@Url.Action("AddToCart", "Product")',
- type: 'POST',
- data: JSON.stringify({ "PID": parseInt(PID) }),
- dataType: "json",
- contentType: "application/json; charset=utf-8",
- success: function (result) {
- $('#dvLoader').hide();
-
- if (result.Status == "True") {
- toastr.success(result.Message);
- clear();
- display();
- }
- else {
- toastr.success(result.Message);
- clear();
- display();
-
- }
- }
- });
Now start your web app..
Step 1 : Open your Visual Studio (the Visual Studio Version should be greater than or equal to 12) and add an MVC internet application as in the following,
I have given it the name "Datatable_Demo".
Step 2 : Create the new Database for this project Name: "PMS" and make the new table of "Product" with property of this table. Make Identity "Yes." Ihave already give one script file for the making of PMS database as well as Table.
Step 3 : Add the Model in this project. right click on your project then click on the Data and choose the ADO.Net Entity Data Model
Select this EF designer from the database.
Step 4 : Make the connction of this database to this project click to connect database and then write your server name on textbox and then select your database name from the dropdown,check if your connection is successful or not.
Step 5 : Add new controller in this project , right click on controller and add a new controller name for this controller
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace DataTable_Demo.Controllers
- {
- public class HomeController : Controller
- {
-
-
-
- public ActionResult Index()
- {
- return View();
- }
-
-
- }
- }
Step 6 : Add view of this Action Result Method. You can add view without layout and also with the layout.
Step 7 : Add Css of bootstrap, toaster css, datatable css and bootrapJs, jqueryjs, datatablejs, toasterjs, bootboxjs, which is described below.
- <!-- Latest compiled and minified CSS -->
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
-
- <!-- jQuery library -->
- <script src="//code.jquery.com/jquery-1.12.4.js"></script>
-
- <!-- Latest compiled JavaScript -->
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
-
- <!-- add thids links for the error message-->
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/css/toastr.css" />
- <script src="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/js/toastr.js"></script>
-
-
- <!--add this link for the datatable-->
- <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
- <link href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap.min.csss" rel="stylesheet" />
-
- <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
- <script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap.min.js"></script>
-
- <script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js" integrity="sha256-4F7e4JsAJyLUdpP7Q8Sah866jCOhv72zU5E8lIRER4w=" crossorigin="anonymous"></script>
Step 8 : Add textbox label and also button in this view like this.
- <div class="col-md-12">
- <div class="col-md-4"></div>
- <div class="col-md-4">
- <div class="col-md-12">
- <label>Product Name :</label>
- <input class="form-control required" type="text" id="txtName" required />
- </div>
- <div class="col-md-12">
- <label>Product Descreption :</label>
- <textarea class="form-control required" id="txtDesc"></textarea>
- </div>
- <div class="col-md-12">
- <label>Product Price :</label>
- <input class="form-control required" onkeypress = "return isNumberKey(event)" id="txtPrice" type="text" required />
- </div>
- <div class="col-md-12">
- <br />
- <input id="btnSave" class="btn btn-success" type="button" value="Save Product" />
- <input id="btnCancel" class="btn btn-danger" type="button" value="Cancel" />
-
- </div>
-
- </div>
- <div class="col-md-4"></div>
-
-
-
- </div>
Step 9 : Add the hidden file for the stored Product_id for the feature use.
- <input type="hidden" id="hdnPID" value="0" />
Step10
Add the Loader in this view
- <div id="dvLoader" class="LoadingDiv" style="display: none;">
- <table style="height: 100%; margin: auto;">
- <tr>
- <td style="vertical-align: middle;">
- <center>
- <img src="http://www.girlsgotit.org/images/ajax-loader.gif" alt="Loading" />
- </center>
- </td>
- </tr>
- </table>
- </div>
Add the style of this loader in this view
- <style>
- .LoadingDiv {
- top: 0;
- left: 0;
- position: fixed;
- opacity: 0.97;
- z-index: 10000000;
- background: Black;
- height: 100%;
- width: 100%;
- margin: auto;
- }
- </style>
Step 10 : Make the AJAX Call for saving and updating the product details in the table in this view.
- <script type="text/javascript">
-
- $(document).ready(function () {
- windowResize();
- $(window).resize(function () {
- windowResize();
- });
- $('#toast-container').find('.toast-top-center').removeClass('.toast-top-center');
- toastr.options = {
- "closeButton": true,
- 'autoWidth': false,
- "debug": false,
- "newestOnTop": true,
- "progressBar": true,
- "positionClass": "toast-top-center",
- "preventDuplicates": false,
- "onclick": null,
- "showDuration": "300",
- "hideDuration": "1000",
- "timeOut": "3000",
- "extendedTimeOut": "1000",
- "showEasing": "swing",
- "hideEasing": "linear",
- "showMethod": "fadeIn",
- "hideMethod": "fadeOut"
- }
-
- $("#btnSave").click(function () {
- var PID = $("#hdnPID").val();
- var Name = $("#txtName").val();
- var Desc = $("#txtDesc").val();
- var Price = parseFloat($("#txtPrice").val()).toFixed(2);
- if (CheckRequiredFields()) {
-
- $('#dvLoader').show();
- $.ajax({
- url: '@Url.Action("SaveAndUpdateProduct", "Home")',
- type: 'POST',
- data: JSON.stringify({ "PID": parseInt(PID), "Name": Name, "Description": Desc, "price": Price }),
- dataType: "json",
- contentType: "application/json; charset=utf-8",
- success: function (result) {
- $('#dvLoader').hide();
-
- if (result.Status == "True") {
- toastr.success(result.Message);
- clear();
- display();
- }
- else {
- toastr.success(result.Message);
- clear();
- display();
-
- }
- }
- });
-
- }
-
- });
-
- $("#btnCancel").click(function () {
- clear();
- });
-
- });
- function clear() {
- $("#txtName").val("");
- $("#txtDesc").val("");
- $("#txtPrice").val("");
- $('#btnSave').val("Save Product");
- $("#hdnPID").val(0);
- }
-
-
- </script>
Step 11 : Add the Validation in this view for the textbox field.
Add the style for creating the red border class
- <style>
- .red_border {
- border: 1px solid #e46262;
- }
- </sctipt>
Add the function of Required field.
- function CheckRequiredFields() {
- var isValid = true;
- $('.required').each(function () {
- if ($.trim($(this).val()) == '') {
- isValid = false;
- $(this).addClass('red_border');
-
-
- }
- else {
- $(this).removeClass('red_border');
-
- }
- });
- return isValid;
- }
This function is used for required validation like this.
Step 12 : Add Method in Home Controller for inserting and updating recoreds in the database.
- public JsonResult SaveAndUpdateProduct(int PID,string Name, string Description, float Price)
- {
- var result = new jsonMessage();
- try
- {
-
- Mst_Product _Mst_Product = new Mst_Product();
- _Mst_Product.PID = PID;
- _Mst_Product.Name = Name;
- _Mst_Product.Description = Description;
- _Mst_Product.Price = Price;
-
-
-
- if (_Mst_Product.PID == 0)
- {
- context.Mst_Product.Add(_Mst_Product);
- result.Message = "your product has been saved success..";
- result.Status = true;
- }
- else
- {
- context.Entry(_Mst_Product).State = EntityState.Modified;
- result.Message = "your product has been updated successfully..";
- result.Status = true;
- }
- context.SaveChanges();
-
-
- }
- catch (Exception ex)
- {
- ErrorLogers.ErrorLog(ex);
- result.Message = "We are unable to process your request at this time. Please try again later.";
- result.Status = false;
- }
- return Json(result, JsonRequestBehavior.AllowGet);
- }
Step 13: Add the Display record table in this index view and also add the script of this display record.
- <div class="col-md-12">
- <table id="tblProduct" class="table table-striped table-bordered" width="100%">
- <thead>
- <tr>
-
- <th >Product_ID</th>
- <th>Name</th>
- <th>Description</th>
- <th>Price</th>
- <th>Action</th>
-
- </tr>
- </thead>
-
- </table>
- </div>
Add the script of the display record
- function display() {
- $('#dvLoader').show();
- Table = $('#tblProduct').DataTable({
-
- "processing": true,
- "serverSide": false,
- "paging": true,
- "ordering": true,
- "info": true,
- "searching": true,
- "bFilter": false,
- "scrollX": "100%",
- "scrollY": ($(window).height() - 500),
- "sScrollXInner": "100%",
- "bScrollCollapse": true,
- "sAjaxSource": '@Url.Action("GetProduct","Home")',
- "bDestroy": true,
- "bLengthChange": true,
- "bPaginate": true,
- "sEmptyTable": "Loading data from server",
-
- "columns": [
-
- {
- "sWidth": "5%",
- "sClass": "TextCenter PID",
- "render": function (data, type, row) {
- return row[0];
- }
- },
- { "sWidth": "5%", "sClass": "TextCenter Name", "render": function (data, type, row ) { return (row[1]); } },
- { "sWidth": "5%", "sClass": "TextCenter Desc", "render": function (data, type, row ) { return (row[2]); } },
- { "sWidth": "5%", "sClass": "TextCenter Price", "render": function (data, type, row ) { return (row[3]); } },
-
- {
- "bSortable": false,
- "sClass": "TextCenter",
- "sWidth": "3%",
- "render": function (data, type, row) {
- return '<center><a href="javascript:void(0);" onclick=deleteData("' + row[0] + '"); return false;> <i class="glyphicon glyphicon-trash"></i></a> <a href="javascript:void(0);" onclick=EditData(this); return false;> <i class="glyphicon glyphicon-edit"></i></a></center>';
- }, "targets": 0,
- }
-
- ],
-
- });
- $('#dvLoader').hide();
- }
Call this function into the document.ready() function and also make the second function
- function windowResize() {
- display();
-
- };
- $(window).resize(function () {
- windowResize();
- });
Call this windowResize(); function in to document.ready()
-
$(document).ready(function () {
windowResize();
-
});
Step 14 : Add Method in Home controller for the Get record and display this record in the Index view.
- public JsonResult GetProduct()
- {
-
- List<Mst_Product> _list = new List<Mst_Product>();
-
- try
- {
- _list = context.Mst_Product.ToList();
- var result = from c in _list
- select new[]
- {
- Convert.ToString( c.PID ),
- Convert.ToString( c.Name ),
- Convert.ToString( c.Description ),
- Convert.ToString( c.Price ),
- };
-
- return Json(new
- {
- aaData= result
- }, JsonRequestBehavior.AllowGet);
- }
-
- catch (Exception ex)
- {
- ErrorLogers.ErrorLog(ex);
- return Json(new
- {
- aaData = new List<string[]> { }
- }, JsonRequestBehavior.AllowGet);
- }
-
- }
Step 15 : Add delete and Update function into script tag
- function deleteData(id) {
- var PID = parseInt(id);
- bootbox.confirm({
- title: 'Remove Customer',
- message: 'Are you sure want to delete this record?',
- buttons: {
- 'cancel': {
- label: 'No',
- className: 'btn-default pull-right'
- },
- 'confirm': {
- label: 'Yes',
- className: 'btn-primary margin-right-5'
- }
- },
- callback: function(result) {
- if (result) {
- $('#dvLoader').show();
- $.ajax({
- url: '@Url.Action("DeleteProduct", "Home")',
- type: 'POST',
- data: JSON.stringify({
- "id": id
- }),
- contentType: 'application/json; charset=utf-8;',
- success: function(result) {
- windowResize();
- $('#dvLoader').hide();
- if (result.Status == "True") {
- toastr.success(result.Message);
- clear();
- } else {
- toastr.success(result.Message);
- }
- }
- });
- }
- }
- });
- }
-
- function EditData(row)
- {
- debugger
- var PID = $(row).closest('tr').find('.PID').html();
- $("#hdnPID").val(parseInt(PID));
- var Name = $(row).closest('tr').find('.Name').html();
- $('#txtName').val(Name);
- var Desc = $(row).closest('tr').find('.Desc').html();
- $('#txtDesc').val(Desc);
- var Price = $(row).closest('tr').find('.Price').html();
- $('#txtPrice').val(Price);
- $('#btnSave').val("Update Product");
- }
Step 17 : Add numeric function because if my texbox is numeric then character value is not allowed.
- function isNumberKey(evt) {
- var charcode = (evt.which) ? evt.which : evt.keycode
- if (charcode > 31 && (charcode < 48 || charcode > 58)
- && evt.keyCode != 35 && evt.keyCode != 36 && evt.keyCode != 37
- && evt.keyCode != 38 && evt.keyCode != 39 && evt.keyCode != 40
- && evt.keyCode != 46) {
- return false;
- }
- else {
- return true;
- }
- }
This function is used like this
- <input class="form-control required" onkeypress = "return isNumberKey(event)" id="txtPrice" type="text" required />
Step 18 : Add Method in Home Controller
- public JsonResult DeleteProduct(int id)
- {
- var result = new jsonMessage();
- try
- {
-
- var product = new Mst_Product { PID = id };
- context.Entry(product).State = EntityState.Deleted;
- context.SaveChanges();
-
-
- result.Message = "your product has been deleted successfully..";
- result.Status = true;
-
- }
- catch (Exception ex)
- {
- ErrorLogers.ErrorLog(ex);
- result.Message = "We are unable to process your request at this time. Please try again later.";
- result.Status = false;
- }
- return Json(result, JsonRequestBehavior.AllowGet);
- }
Now you can perform all the operations on this Project, all files are validated in this project using jquery functions.
Summary
This article describes how to perform basic CRUD operations in an Asp.Net MVC application using Entity Framework with Ajax call and jquery using Datatable Grid ,Toaster messagebox and also Bootstrap css.