Skip to main content

MVC CRUD using AJAX passing model data for POST-PUT-GET-Delete using Entity Framework

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//


------------------------------------------------------------------------------

namespace UserManagementWebApp.DataAccess
{
    using System;
    using System.Collections.Generic;
   
    public partial class Customer
    {
        public int CustId { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Country { get; set; }
        public Nullable<long> Contact { get; set; }
        public string Email { get; set; }
    }
}

--------------------------------------------------------------------------------
@model UserManagementWebApp.DataAccess.Customer

@{
    Layout = null;
}

<!DOCTYPE html>

<script src="~/Scripts/jquery-1.10.2.min.js"></script>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>AddCustomer</title>
</head>
<body>
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
       
    <div class="form-horizontal">
        <h4>Customer</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.CustId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.CustId, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.CustId, "", new { @class = "text-danger" })
                            <input type="button" id="btnSearch" value="Search" onclick="SearchCustomer()" />
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.State, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.State, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.State, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Country, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Country, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Country, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Contact, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Contact, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Contact, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="button" value="Create" onclick="SaveCustomer()" class="btn btn-default" />
                <input type="button" value="Update" onclick="UpdateCustomer()" class="btn btn-default" />
                <input type="button" value="Delete" onclick="DeleteCustomer()" class="btn btn-default" />
                <input type="button" value="Reset" onclick="ResetCustomer()" class="btn btn-default" />
            </div>
        </div>
    </div>
    }
   
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
</body>
</html>
<script>
    function SaveCustomer() {
        debugger;
        var customer = new Object;
        customer.Name = $('#Name').val();
        customer.Address = $('#Address').val();
        customer.City = $('#City').val();
        customer.State = $('#State').val();
        customer.Country = $('#Country').val();
        customer.Contact = $('#Contact').val();
        customer.Email = $('#Email').val();

        $.ajax({
            url: 'ManageCustomer/AddCustomer',
            type: 'Post',
            data: customer,
            dataType: 'json',
            ContentType: 'application/json',
            success: function (data) {
                if (data != null) {
                    alert('Data saved successfully');
                }
            }
        })
    }
    function SearchCustomer() {
        let custId = $('#CustId').val();
        $.ajax({
            url:'ManageCustomer/GetCustomerById',
            type: 'Get',
            data: {custId: custId},
            dataType: 'json',
            success: function (result) {
                if (result != null) {
                    BindCustomerData(result)
                }
            }
        })
    }
    function BindCustomerData(result) {
        $('#Name').val(result.Name);
        $('#Address').val(result.Address);
        $('#City').val(result.City);
        $('#State').val(result.State);
        $('#Country').val(result.Country);
        $('#Contact').val(result.Contact);
        $('#Email').val(result.Email);
    }
    function UpdateCustomer() {
        debugger;
        var customer = new Object;
        customer.CustId = $('#CustId').val();
        customer.Name = $('#Name').val();
        customer.Address = $('#Address').val();
        customer.City = $('#City').val();
        customer.State = $('#State').val();
        customer.Country = $('#Country').val();
        customer.Contact = $('#Contact').val();
        customer.Email = $('#Email').val();

        $.ajax({
            url: 'ManageCustomer/UpdateCustomer?id=' + $('#CustId').val(),
            type: 'Put',
            data: customer,
            dataType: 'json',
            ContentType: 'application/json',
            success: function (data) {
                debugger;
                if (data != null) {
                    alert('Data Updated successfully');
                }
            }
        })
    }
    function DeleteCustomer() {
        let custId = $('#CustId').val();
        $.ajax({
            url: 'ManageCustomer/DeleteCustomer?custId=' + $('#CustId').val(),
            type: 'Delete',
            dataType: 'json',
            success: function (result) {
                if (result != null) {
                    alert('Data deleted successfully');
                    ResetCustomer();
                }
            }
        })
    }
    function ResetCustomer() {
        $('#CustId').val('');
        $('#Name').val('');
        $('#Address').val('');
        $('#City').val('');
        $('#State').val('');
        $('#Country').val('');
        $('#Contact').val('');
        $('#Email').val('');
    }
</script>

-----------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UserManagementWebApp.DataAccess;

namespace UserManagementWebApp.Controllers
{
    public class ManageCustomerController : Controller
    {
        UserManagementEntities _dbEntity = new UserManagementEntities();

        // GET: ManageCustomer
        public ActionResult AddCustomer()
        {
            return View();
        }

        [HttpPost]
        public JsonResult AddCustomer(Customer customer)
        {
            _dbEntity.Customers.Add(customer);
            _dbEntity.SaveChanges();
            return Json(customer, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public JsonResult GetCustomerById(int? custId)
        {
            return Json(_dbEntity.Customers.FirstOrDefault(t => t.CustId == custId), JsonRequestBehavior.AllowGet);
        }

        [HttpPut]
        public JsonResult UpdateCustomer(int? id, Customer customer)
        {
            _dbEntity.Customers.Add(customer);
            _dbEntity.Entry(customer).State = System.Data.Entity.EntityState.Modified; // entity is modified
            _dbEntity.SaveChanges();
            return Json(customer, JsonRequestBehavior.AllowGet);
        }
           
        [HttpDelete]
        public JsonResult DeleteCustomer(int? custId)
        {
            Customer cust = _dbEntity.Customers.FirstOrDefault(t => t.CustId == (int)custId);
            _dbEntity.Customers.Remove(cust);
            _dbEntity.SaveChanges();
            return Json(custId, JsonRequestBehavior.AllowGet);
        }
    }
}

Comments

Popular posts from this blog

Asp.net grid CRUD with ADO.NET

Asp.net grid CRUD with ADO.NET A GridView is a graphical control element that presents a tabular view of data. A typical Grid View also supports some or all of the following: Clicking a column header to change the sort order of the Grid. Dragging column headers to change their size and their order. The GridView control displays the values of a data source in a table. Each column represents a field, while each row represents a record. Support to data source controls, such as SqlDataSource. Support sort capabilities. Support update and delete capabilities. Support paging capabilities. Support row selection capabilities. Code behind feature access to the GridView object model to dynamically set properties, handle events, and so on. Many key fields. Many data fields for the hyperlink columns. Customized style layout through themes and styles using css and javascript. The following operations can be performed using GridView control in ASP.NET using C# code behind. Fea...

MVC Action Filters using log4net

Add log4net dll reference to your MVC project ------------------------------------------------------------------------------ Create following  model inside your models folder ------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Web; using System.Web.Mvc; namespace MVCWebApp.Models {     public class LoggingFilterAttribute : ActionFilterAttribute     {         #region Logging         /// <summary>         /// Access to the log4Net logging object         /// </summary>         protected static readonly log4net.ILog log =           log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);         pri...

Asp.net MVC Grrid with search add update and delete

CRUD Operations Using jqGrid In ASP.NET MVC 1. Create a new MVC Project and give the name for your project. To create a new MVC  project, Click File > New > Project or press CTRL + SHIFT + N.     2. Select MVC as a project Template with Individual Authentication.     3. Now for creating the table into the database using Code First Approach, I am creating a folder with name "Entities". For creating the folder inside the project right click on the folder and click on Add then click on  New Folder .     Now give the name for the folder as "Entities" .   4.  Add a class inside  Entities  folder with Name "StudentMaster.cs". You can follow the below figure to add class:   Now one dialog box will be open give the name for that class as "StudentMaster.cs".     5. Now write the following code into "StudentMaster". using  System;   using  System....