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...

.NET Interview Preparation for Experienced Candidate

.NET Real Time Interview Questionnaire  for Experienced Candidate Architecture Level Questions 1.        SOLID Principles 2.        Dependency Injection 3.        Design Patterns 4.        SingleTon Patterns 5.        Factory Patterns 6.        Repository Patterns 7.        Bidge Patterns 8.        Strategy Patterns 9.        Software Methodology ( Agile) 10.    Realtime Project 11.    Security ( Authentication & Authorisation) 12.    Lazy Loading 13.    Caching 14.    Performance Tuning 15.    Loosely coupling 16.    Logger 17.    IIS Deployment   C# Basic & Advanced 18.    Garbage collec...

Angular NgModules - angular modules simple example - Angular 7-6-5-4-3-2-1-AngularJs

Angular Module In Angular, Modules are the collection of the Components, Service directives, and Pipes which are related such that they can be combined to form a module.   A module is a collection of services, directives, controllers, filters, and configuration information.  angular . module  is used to configure the  What's an NgModule NgModules are simply TypeScript classes decorated with the  @NgModule  decorator imported from the  @angular/core  package. Modules provide a way for developers to organize their code and they are particularly helpful for managing large apps. In Angular, Modules are the collection of the Components, Service directives, and Pipes which are related such that they can be combined to form a module.