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

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 page life cycle

ASP.Net Page Life Cycle What ASP.Net Page Life Cycle is   When a page is requested by the user from the browser, the request goes through a series of steps and many things happen in the background to produce the output or send the response back to the client. The periods between the request and response of a page is called the "Page Life Cycle". Request:  Start of the life cycle (sent by the user). Response:  End of the life cycle (sent by the server). Now let's see how to initiate a request.       Now we"ll see the entire process of the Page Life Cycle.   First the client requests a page or resource from the browser. The request is passed to the IIS server. The IIS server starts the initial processing of the request and one of the basic extensions, like .aspx or .ascx, loads the "ASPNET_ISAP.dll". The ASPNET_ISAP.dll generates the "HttpRuntime" class and assigns it to the worker process. The HttpRuntime class generates...

AB Info Technology