Subscribe Us

LightBlog

Wednesday, 28 October 2020

October 28, 2020

Crud Operation Using AJAX in ASP.NET MVC

using System.Data.Entity;

using System.Data;

using Asp.NETMVCCRUD.Models;

using System.Data.SqlClient;

namespace Asp.NETMVCCRUD.Controllers

{

    public class EmployeeController : Controller

    {

        private SqlConnection con;

        private SqlCommand cmd;

        private void connection()

        {

            con = new SqlConnection("Data Source=.;Integrated Security=true;Initial   Catalog=MvcCRUDDB");

        }

        public ActionResult Index()

        {

          return View();

        }

        public ActionResult GetData(int id=0)

        {

            List<Employee> emplst = new List<Employee>();

            DataSet ds = new DataSet();

            connection();

            cmd = new SqlCommand("USP_GetEmployeeDetails", con);

            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.AddWithValue("@EmployeeID",id);

            con.Open();

            SqlDataAdapter da = new SqlDataAdapter(cmd);

            da.Fill(ds);

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)

            {

                Employee empobj = new Employee();

                empobj.EmployeeID = Convert.ToInt32(ds.Tables[0].Rows[i]["EmployeeID"].ToString());

                empobj.Name = ds.Tables[0].Rows[i]["Name"].ToString();

                empobj.Position = ds.Tables[0].Rows[i]["Position"].ToString();

                empobj.Office = ds.Tables[0].Rows[i]["Office"].ToString();

                empobj.Age = Convert.ToInt32(ds.Tables[0].Rows[i]["Age"].ToString());

                empobj.Salary = Convert.ToInt32(ds.Tables[0].Rows[i]["Salary"].ToString());

                empobj.Gender = ds.Tables[0].Rows[i]["Gender"].ToString();

                empobj.isGujarati = Convert.ToBoolean(ds.Tables[0].Rows[i]["isGujarati"].ToString());

                empobj.isHindi = Convert.ToBoolean(ds.Tables[0].Rows[i]["isHindi"].ToString());

                empobj.isEnglish = Convert.ToBoolean(ds.Tables[0].Rows[i]["isEnglish"].ToString());

                empobj.City = ds.Tables[0].Rows[i]["City"].ToString();

                empobj.State = ds.Tables[0].Rows[i]["State"].ToString();

                empobj.Country = ds.Tables[0].Rows[i]["Country"].ToString();

                emplst.Add(empobj);

            }

            con.Close();

            return Json(new { data = emplst }, JsonRequestBehavior.AllowGet);

        }


        public JsonResult CountryData()

        {

            List<Employee> emplst = new List<Employee>();

            DataSet ds = new DataSet();

            connection();

            cmd = new SqlCommand("usp_getcountry_data", con);

            cmd.CommandType = CommandType.StoredProcedure;

            con.Open();

            SqlDataAdapter da = new SqlDataAdapter(cmd);

            da.Fill(ds);

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)

            {

                Employee empobj = new Employee();

                empobj.Countryid = ds.Tables[0].Rows[i]["Countryid"].ToString();

                empobj.Country = ds.Tables[0].Rows[i]["Country"].ToString();

                emplst.Add(empobj);

            }

            con.Close();

            return Json(new { data = emplst }, JsonRequestBehavior.AllowGet);

        }


        public JsonResult StateData(string country_id)

        {

            List<Employee> emplst = new List<Employee>();

            DataSet ds = new DataSet();

            connection();

            cmd = new SqlCommand("usp_getstate_data", con);

            cmd.Parameters.AddWithValue("@country_id", country_id);

            cmd.CommandType = CommandType.StoredProcedure;

            con.Open();

            SqlDataAdapter da = new SqlDataAdapter(cmd);

            da.Fill(ds);

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)

            {

               Employee empobj = new Employee();

                empobj.Stateid = ds.Tables[0].Rows[i]["stateid"].ToString();

                empobj.State = ds.Tables[0].Rows[i]["state"].ToString();

                emplst.Add(empobj);

            }

            con.Close();

            return Json(new { data = emplst }, JsonRequestBehavior.AllowGet);

        }


        public JsonResult CityData(string state_id)

        {

            List<Employee> emplst = new List<Employee>();

            DataSet ds = new DataSet();

            connection();

            cmd = new SqlCommand("usp_getcity_data", con);

            cmd.Parameters.AddWithValue("@state_id", state_id);

            cmd.CommandType = CommandType.StoredProcedure;

            con.Open();

            SqlDataAdapter da = new SqlDataAdapter(cmd);

            da.Fill(ds);

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)

            {

                Employee empobj = new Employee();

              empobj.Cityid = ds.Tables[0].Rows[i]["Cityid"].ToString();

                empobj.City = ds.Tables[0].Rows[i]["City"].ToString();

                emplst.Add(empobj);

            }

            con.Close();

            return Json(new { data = emplst }, JsonRequestBehavior.AllowGet);

        }


        public ActionResult EmployeeData(int id)

        {

            return Json(GetData(id));

        }


        public ActionResult AddOrEdit(int id)

        {

            return View(GetData(id));

        }


        [HttpPost]

        public ActionResult AddOrEdit(Employee empobj, string Gujarati, string Hindi, string English)

        {

            try

            {

                connection();

                if (Gujarati == "true")

                {

                    empobj.isGujarati = true;

                }

                else

                {

                    empobj.isGujarati = false;

                }

                if (Hindi == "true")

                {

                    empobj.isHindi = true;

                }

                else

                {

                    empobj.isHindi = false;

                }

                if (English == "true")

               {

                    empobj.isEnglish = true;

                }

               else

                {

                    empobj.isEnglish = false;

                }

                connection();

                string spname = "USP_Add_Edit_Employee";

                SqlCommand cmd = new SqlCommand(spname, con);

                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.AddWithValue("@Name", empobj.Name);

                cmd.Parameters.AddWithValue("@Position", empobj.Position);

                cmd.Parameters.AddWithValue("@Office", empobj.Office);

                cmd.Parameters.AddWithValue("@Age", empobj.Age);

                cmd.Parameters.AddWithValue("@Salary", empobj.Salary);

               cmd.Parameters.AddWithValue("@Gender", empobj.Gender);

                cmd.Parameters.AddWithValue("@isGujarati", empobj.isGujarati);

                cmd.Parameters.AddWithValue("@isHindi", empobj.isHindi);

                cmd.Parameters.AddWithValue("@isEnglish", empobj.isEnglish);

                cmd.Parameters.AddWithValue("@Cityid", empobj.Cityid);

                cmd.Parameters.AddWithValue("@City", empobj.Cityval);

                cmd.Parameters.AddWithValue("@Stateid", empobj.Stateid);

                cmd.Parameters.AddWithValue("@State", empobj.Stateval);

                cmd.Parameters.AddWithValue("@Countryid", empobj.Countryid);

                cmd.Parameters.AddWithValue("@Country", empobj.Countryval);


                con.Open();

                int i = cmd.ExecuteNonQuery();

                con.Close();

            }

            catch (Exception ex)

            {

                ex.Message.ToString();

                return View("Error");

            }

            return RedirectToAction("Index");

        }



        [HttpPost]

        public ActionResult delete(int id)

        {

            try

            {

                Employee empobj = new Employee();        

                connection();

                string spname = "USP_deleteEmployee";

                SqlCommand cmd = new SqlCommand(spname, con);

                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.AddWithValue("@EmployeeID", id);

                con.Open();

                int i = cmd.ExecuteNonQuery();

                con.Close();

            }

            catch (Exception ex)

           {

                ex.Message.ToString();

                return View("Error");

            }

            return RedirectToAction("Index");

        }

    }

}

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


    public class Employee
    {
        public int EmployeeID { get; set; }
        public string Name { get; set; }
        public string Position { get; set; }
        public string Office { get; set; }
        public int Age { get; set; }
        public int Salary { get; set; }
        public string Gender { get; set; }
        public bool isGujarati { get; set; }
        public bool isHindi { get; set; }
        public bool isEnglish { get; set; }
        public string Countryid { get; set; }
        public string Country { get; set; }
        public string Countryval { get; set; }

        //State property
        public string Stateid { get; set; }
        public string State { get; set; }
        public string Stateval { get; set; }

        //City property
        public string Cityid { get; set; }
        public string City { get; set; }
        public string Cityval { get; set; }
    }
}

-----------------------------------------------------------------------------------------
AddOrEdit.cshtml

@model IEnumerable<Asp.NETMVCCRUD.Models.Employee>
@{
    Layout = null;
}

@using (Html.BeginForm("AddOrEdit", "Employee", FormMethod.Post, new { onsubmit = "return SubmitForm(this)" }))
{
    @Html.HiddenFor(model => model.EmployeeID)
    <div class="form-group">
        @Html.LabelFor(model => model.Name, new { @class = "control-label" })
        @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Name)
        @Html.HiddenFor(model => model.Countryid)
        @Html.HiddenFor(model => model.Stateid)
        @Html.HiddenFor(model => model.Cityid)
        @Html.HiddenFor(model => model.Countryval)
        @Html.HiddenFor(model => model.Stateval)
        @Html.HiddenFor(model => model.Cityval)
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.Position, new { @class = "control-label" })
        @Html.EditorFor(model => model.Position, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Position)
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.Office, new { @class = "control-label" })
        @Html.EditorFor(model => model.Office, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Office)
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.Age, new { @class = "control-label" })
        @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Age)
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.Salary, new { @class = "control-label" })
        <div class="input-group">
            <span class="input-group-addon">
                <i class="fa fa-inr" aria-hidden="true"></i>
            </span>
            @Html.EditorFor(model => model.Salary, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Salary)
        </div>
        <br />
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.Gender, new { @class = "control-label" })&nbsp;
        <label class="radio-inline">
            @Html.RadioButtonFor(model => model.Gender, "Male", new { @name = " Gender" })
            Male
        </label>
        <label class="radio-inline">
            @Html.RadioButtonFor(model => model.Gender, "Female", new { @name = " Gender" })
            Female
        </label>
        @Html.ValidationMessageFor(model => model.Gender)
    </div>
    <div class="form-group" id="AjaxCheckbox">
        <label class="control-label">
            Languages Known
        </label>

        <label class="checkbox-inline">
            @Html.CheckBox("Gujarati")
            @Html.ValidationMessageFor(model => model.isGujarati)
            Gujarati
        </label>
        <label class="checkbox-inline">
            @Html.CheckBox("Hindi")
            @Html.ValidationMessageFor(model => model.isHindi)
            Hindi
        </label>
        <label class="checkbox-inline">
            @Html.CheckBox("English")
            @Html.ValidationMessageFor(model => model.isEnglish)
            English
        </label>
    </div>
    <select id="Country" name="Country" class="form-control"></select>
    <select id="State" name="State" class="form-control"></select>
    <select id="City" name="City" class="form-control"></select>

    <div class="form-group">
        <input type="submit" value="Submit" class="btn btn-primary" />
        <input type="reset" value="Reset" class="btn" />
    </div>
}

<script src="~/Scripts/jquery-1.12.4.min.js"></script>
<script>
    var ddlCountry = $("#Country");
    ddlCountry.empty().append('<option selected="selected" value="0" disabled = "disabled">Loading.....</option>');
    $.ajax({
        type: "GET",
        url: "/Employee/CountryData",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            ddlCountry.empty().append('<option selected="selected" value="0">Please select</option>');
            $.each(response.data, function () {
                ddlCountry.append($("<option></option>").val(this['Countryid']).html(this['Country']));
            });
        }
    });

    $("#Country").change(function () {
        var id = $(this).val();
        var ddlState = $("#State");
        ddlState.empty().append('<option selected="selected" value="0" disabled = "disabled">Loading.....</option>');
        $.ajax({
            type: "GET",
            url: "/Employee/StateData",
            data: { country_id: id },
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                ddlState.empty().append('<option selected="selected" value="0">Please select</option>');
                $.each(response.data, function () {
                    ddlState.append($("<option></option>").val(this['Stateid']).html(this['State']));
                });
                $("#Countryid").val($("#Country").val());
                $("#Countryval").val($("#Country option:selected").text());
            }
        });
    });
    
    $("#State").change(function () {
        var id = $(this).val();
        var ddlState = $("#City");
        ddlState.empty().append('<option selected="selected" value="0" disabled = "disabled">Loading.....</option>');
        $.ajax({
            type: "GET",
            url: "/Employee/CityData",
            data: { state_id: id },
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                ddlState.empty().append('<option selected="selected" value="0">Please select</option>');
                $.each(response.data, function () {
                    ddlState.append($("<option></option>").val(this['Cityid']).html(this['City']));
                });
                $("#Stateval").val($("#State option:selected").text());
                $("#Stateid").val($("#State").val());
            }
        });

        $("#City").change(function () {
            $("#Cityval").val($("#City option:selected").text());
            $("#Cityid").val($("#City").val());
        });
    });
</script>
---------------------------------------------------------------------------------------
Index.cshtml   
@{
    ViewBag.Title = "Employee List";
}

<h2>Employee CRUD Operations</h2>
<a class="btn btn-success" style="margin-bottom:10px" onclick="PopupForm('@Url.Action("AddOrEdit","Employee")')"><i class="fa fa-plus"></i> Add New</a>
<table id="employeeTable" class="table table-striped table-bordered" style="width:100%">
    <thead>
        <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Salary</th>
            <th>Gender</th>
            <th>Languages Known</th>
            <th>Country</th>
            <th>State</th>
            <th>City</th>
            <th></th>
        </tr>
    </thead>
</table>

<link href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

@section scripts{
    @*<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap.min.js"></script>*@
    <script>
        var Popup, dataTable;
        $(document).ready(function () {
            dataTable = $("#employeeTable").DataTable({
                "ajax": {
                    "url": "/Employee/GetData",
                    "type": "GET",
                    "datatype": "json"
                },
                "columns": [
                    { "data": "Name" },
                    { "data": "Position" },
                    { "data": "Office" },
                    { "data": "Age" },
                    { "data": "Salary" },
                    { "data": "Gender" },
                    {
                        "data": null,
                        "render": function (empdata) {
                            //debugger
                            //console.log(empdata)
                            var gujarati = (empdata.isGujarati === false) ? " " : "Gujarati";
                            var hindi = (empdata.isHindi === false) ? " " : "Hindi";
                            var english = (empdata.isEnglish === false) ? " " : "English";
                            return gujarati + " " + hindi + " " + english;
                        }
                    },
                    { "data": "Country" },
                    { "data": "State" },
                    { "data": "City" },
                    { "data":"EmployeeID" , "render" : function (data) {
                        return "<a class='btn btn-default btn-sm' onclick=PopupForm('@Url.Action("AddOrEdit", "Employee")/" +data+ "')><i class='fa fa-pencil'></i> Edit</a><a class='btn btn-danger btn-sm' style='margin-left:5px' onclick=Delete("+data+")><i class='fa fa-trash'></i> Delete</a>";
                    },
                        "paging": true,
                        "sort": false,
                        "orderable": true,
                        "searchable": true,
                        "scrollY":200,
                        "width": "300px"
                    }
                ],
                "language": {

                    "emptyTable" : "No data found, Please click on <b>Add New</b> Button"
                }
            });
        });

        function PopupForm(url) {
            var formDiv = $('<div/>');
            $.get(url)
                .done(function (response) {
                console.log(response)
                formDiv.html(response);
                Popup = formDiv.dialog({
                    autoOpen: true,
                    resizable: false,
                    title: 'Fill Employee Details',
                    height: 500,
                    width: 700,
                    close: function () {
                        Popup.dialog('destroy').remove();
                    }

                });
            });
        }

        function SubmitForm(form) {
            $.validator.unobtrusive.parse(form);
            if($(form).valid()){
                $.ajax({
                    type : "POST",
                    url : form.action,
                    data: $(form).serialize(),
                    success : function (data) {
                        if(data.success)
                        {
                            Popup.dialog('close');
                            dataTable.ajax.reload();

                            $.notify(data.message,{
                                globalPosition :"top center",
                                className : "success"
                            })

                        }
                    }
                });
            }
            return false;
        }

        function Delete(id) {
            if(confirm('Are You Sure to Delete this Employee Record ?'))
            {
                $.ajax({
                    type: "POST",
                    url: '@Url.Action("Delete","Employee")/' + id,
                    success: function (data) {
                        if (data.success)
                        {
                            dataTable.ajax.reload();

                            $.notify(data.message, {
                                globalPosition: "top center",
                                className: "success"
                            })

                        }
                    }

                });
            }
        }
    </script>
}


Tables:
CREATE TABLE [dbo].[countryState](
[StateId] [int] NOT NULL,
[CountryId] [int] NULL,
[State] [varchar](30) NULL,
PRIMARY KEY CLUSTERED 
(
[StateId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

----------------------------------------------
CREATE TABLE [dbo].[Employee](
[EmployeeID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
[Position] [varchar](50) NULL,
[Office] [varchar](50) NULL,
[Age] [int] NULL,
[Salary] [int] NULL,
[Gender] [varchar](50) NULL,
[isGujarati] [bit] NULL,
[isHindi] [bit] NULL,
[isEnglish] [bit] NULL,
[CityId] [int] NULL,
[City] [varchar](30) NULL,
[StateId] [int] NULL,
[State] [varchar](30) NULL,
[CountryId] [int] NULL,
[Country] [varchar](30) NULL,
 CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED 
(
[EmployeeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
------------------------------------------------------------------------------
CREATE TABLE [dbo].[stateCity](
[CityId] [int] NULL,
[StateId] [int] NULL,
[City] [varchar](30) NULL
) ON [PRIMARY]
GO
------------------------------------------------------------------------------
CREATE TABLE [dbo].[tbl_city](
[City_id] [int] IDENTITY(1,1) NOT NULL,
[State_id] [int] NULL,
[City] [nvarchar](max) NULL,
 CONSTRAINT [PK_tbl_city] PRIMARY KEY CLUSTERED 
(
[City_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO


CREATE TABLE [dbo].[tbl_Country](
[Country_id] [int] IDENTITY(1,1) NOT NULL,
[Country_Name] [nvarchar](50) NULL,
 CONSTRAINT [PK_tbl_Country] PRIMARY KEY CLUSTERED 
(
[Country_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO


CREATE TABLE [dbo].[tbl_state](
[State_id] [int] IDENTITY(1,1) NOT NULL,
[Country_id] [int] NULL,
[State] [nvarchar](max) NULL,
 CONSTRAINT [PK_tbl_state] PRIMARY KEY CLUSTERED 
(
[State_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO


GO
CREATE PROCEDURE [dbo].[USP_Add_Edit_Employee]  
 @EmployeeID int = 0,  
 @Name varchar(50),  
 @Position varchar(50),  
 @Office varchar(50),  
 @Age int,  
 @Salary int,  
 @Gender varchar(50),  
 @isGujarati bit,  
 @isHindi bit,  
 @isEnglish bit,
 @Cityid varchar(30),
 @City varchar(30),  
 @Stateid varchar(30),
 @State varchar(30),
  @Countryid varchar(30),
 @Country varchar(30),  
 @result int = 0 out  
AS  
BEGIN  
 SET NOCOUNT ON;  
  
 if @EmployeeID=0  
  BEGIN  
   insert into Employee(Name, Position, Office,Age,Salary,Gender,isGujarati,isHindi,isEnglish,CityId,City,StateId,State,CountryId,Country)  
   values(@Name,@Position,@Office,@Age,@Salary,@Gender,@isGujarati,@isHindi,@isEnglish,@Cityid,@City,@Stateid,@State,@Countryid,@Country)  
   set @result = SCOPE_IDENTITY()  
  END  
 ELSE  
 BEGIN  
  update Employee set  
  Name = @Name,  
  Position = @Position,  
  Office =@Office,  
  Age = @Age,  
  Salary =@Salary,  
  Gender =@Gender,  
  isGujarati =@isGujarati,  
  isHindi =@isHindi,  
  isEnglish = @isEnglish,
  CityId = @Cityid,
  City = @City,
  StateId= @Stateid,
  State= @State,
  CountryId = @Countryid,
  Country = @Country  
  where EmployeeID=@EmployeeID  
  select @EmployeeID  
 END  
END  
  
GO

Create PROCEDURE [dbo].[USP_deleteEmployee]
@EmployeeID int
AS
BEGIN
SET NOCOUNT ON;
Delete from Employee where EmployeeID=@EmployeeID
END

GO

CREATE proc [dbo].[usp_getcity_data]
@state_id varchar(15)
as
select cityid,city from stateCity where stateid=@state_id

GO

CREATE proc [dbo].[usp_getcountry_data]
as
select CountryId,Country as country from Country
GO


CREATE PROCEDURE [dbo].[USP_GetEmployeeDetails]
@EmployeeID int = 0
AS
BEGIN
SET NOCOUNT ON;

if @EmployeeID=0
BEGIN
select * from Employee
END
ELSE
BEGIN
select * from Employee where EmployeeID=@EmployeeID
END
END

GO

CREATE proc [dbo].[usp_getstate_data]
@country_id varchar(15)
as
select stateid,state  from countryState where countryid=@country_id
GO
USE [master]
GO
ALTER DATABASE [MvcCRUDDB] SET  READ_WRITE 
GO




October 28, 2020

CRUD Operations In Angular 7 Using Web API (PART-2)

 Step 5. Build UI Application

 
Now, we create the Web application in Angular 7 that will consume Web API.
First we have to make sure that we have Angular CLI installed. 
Open command prompt and type below code and press ENTER:
 
npm install -g @angular/cli
 
Now, open Visual Studio Code and create a project.
Open TERMINAL in Visual Studio Code and type the following syntax to create a new project. We name it Angularcrud.
 
ng new Angularcrud
 
After that, hit ENTER. It will take a while to create the project.
Now, we can create some components to provide the UI.
 
I'm going to create a new component, Employee.
 
Go to the TERMINAL and go our angular project location using the following command:
 
cd projectName
 Now, write the following command that will create a component.
 
ng g c employee 
 
Press ENTER.
 
Note: you can use see the component is created.
 
Step 6. Create a Service
 
Now, we will create a service.
 
Open the TERMINAL and write the below command:
 
ng g s employee
 
Press ENTER and you will see two service files.
Now, we create a class like model class.
 
Open TERMINAL and write the below command:
 
ng g class employee
 
Now, write all properties of the Employee class related to an employee that matches with the database. 
  1. export class Employee {  
  2.     EmpId: string;  
  3.     EmpName: string;  
  4.     DateOfBirth: Date;  
  5.     EmailId: string;  
  6.     Gender: string;  
  7.     Address: string;  
  8.     PinCode: string;  
  9. }  

Now, open employee.service.ts and first import necessary class and libraries and then make calls to the WebAPI methods. 
  1. import { Injectable } from '@angular/core';  
  2. import { HttpClient } from '@angular/common/http';  
  3. import { HttpHeaders } from '@angular/common/http';  
  4. import { Observable } from 'rxjs';  
  5. import { Employee } from './employee';  
  6.   
  7. After that we write all methods related to consume web in employee.service.ts  
  8.  @Injectable({  
  9.   providedIn: 'root'  
  10. })  
  11.   
  12. export class EmployeeService {  
  13.   url = 'http://localhost:65389/Api/Employee';  
  14.   constructor(private http: HttpClient) { }  
  15.   getAllEmployee(): Observable<Employee[]> {  
  16.     return this.http.get<Employee[]>(this.url + '/AllEmployeeDetails');  
  17.   }  
  18.   getEmployeeById(employeeId: string): Observable<Employee> {  
  19.     return this.http.get<Employee>(this.url + '/GetEmployeeDetailsById/' + employeeId);  
  20.   }  
  21.   createEmployee(employee: Employee): Observable<Employee> {  
  22.     const httpOptions = { headers: new HttpHeaders({ 'Content-Type''application/json'}) };  
  23.     return this.http.post<Employee>(this.url + '/InsertEmployeeDetails/',  
  24.     employee, httpOptions);  
  25.   }  
  26.   updateEmployee(employee: Employee): Observable<Employee> {  
  27.     const httpOptions = { headers: new HttpHeaders({ 'Content-Type''application/json'}) };  
  28.     return this.http.put<Employee>(this.url + '/UpdateEmployeeDetails/',  
  29.     employee, httpOptions);  
  30.   }  
  31.   deleteEmployeeById(employeeid: string): Observable<number> {  
  32.     const httpOptions = { headers: new HttpHeaders({ 'Content-Type''application/json'}) };  
  33.     return this.http.delete<number>(this.url + '/DeleteEmployeeDetails?id=' +employeeid,  
  34.  httpOptions);  
  35.   }  
  36. }  
Our service is completed now.
 
If you consume the Web API, Angular blocks the URL and we called this issue CORS(Cross OriginResource Sharing).
 
First, let's resolve this problem.
 
Go to the Web API project.
Download a Nuget package for CORS. Go to NuGet Package ManagerConsole install this package:
Install-Package Microsoft.AspNet.WebApi.Cors

After that, go to App_Start folder in Web API project and open WebApiConfig.cs class. Here, modify the Register method with the below code.
  1. Add namespace  
  2. using System.Web.Http.Cors;  
  3. var cors = new EnableCorsAttribute("*","*","*");//origins,headers,methods   
  4. config.EnableCors(cors);  
Step 7. Install and Configure Angular Material Theme
 
As I said earlier, we will use the Angular Material theme to create a rich, interactive, and device-oriented UI for our Web app. 
 
Let's install Install Angular Material theme.
 
Open TERMINAL again and write the below command:
 
npm install --save @angular/material @angular/cdk @angular/animations


Now, let's all required libraries in app.module.ts. We also import a date picker because we'll use the date picker for date of birth field.
 
Now, open app.module.ts class and write the below code.
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { EmployeeService } from './employee.service';  
  4. import { FormsModule, ReactiveFormsModule } from '@angular/forms';  
  5. import { HttpClientModule, HttpClient } from '@angular/common/http';  
  6. import {  
  7.   MatButtonModule, MatMenuModule, MatDatepickerModule,MatNativeDateModule , MatIconModule, MatCardModule, MatSidenavModule,MatFormFieldModule,  
  8.   MatInputModule, MatTooltipModule, MatToolbarModule  
  9. } from '@angular/material';  
  10. import { MatRadioModule } from '@angular/material/radio';  
  11. import { BrowserAnimationsModule } from '@angular/platform-browser/animations';  
  12.   
  13. import { AppRoutingModule } from './app-routing.module';  
  14. import { AppComponent } from './app.component';  
  15. import { EmployeeComponent } from './employee/employee.component';  
  16.   
  17. @NgModule({  
  18.   declarations: [  
  19.     AppComponent,  
  20.     EmployeeComponent  
  21.   ],  
  22.   imports: [  
  23.     BrowserModule,  
  24.     FormsModule,  
  25.     ReactiveFormsModule,  
  26.     HttpClientModule,  
  27.     BrowserAnimationsModule,  
  28.     MatButtonModule,  
  29.     MatMenuModule,  
  30.     MatDatepickerModule,  
  31.     MatNativeDateModule,  
  32.     MatIconModule,  
  33.     MatRadioModule,  
  34.     MatCardModule,  
  35.     MatSidenavModule,  
  36.     MatFormFieldModule,  
  37.     MatInputModule,  
  38.     MatTooltipModule,  
  39.     MatToolbarModule,  
  40.     AppRoutingModule  
  41.   ],  
  42.   providers: [HttpClientModule, EmployeeService,MatDatepickerModule],  
  43.   bootstrap: [AppComponent]  
  44. })  
  45. export class AppModule { }  
 Now, we have to import library in styles.css file.
  1. @import '@angular/material/prebuilt-themes/indigo-pink.css';  
Step 8. Design HTML
 
Let's design our HTML page now.
 
Open employee.component.html and write the below code.
  1. <div class="container">  
  2.   
  3. <mat-card>  
  4.   <mat-toolbar color="accent">  
  5.     <div align="center" style="color:white;text-align: right;">  
  6.       CRUD operation in Angular 7 using Web api and Sql Database  
  7.     </div>    
  8.   </mat-toolbar>  
  9. <br><br>  
  10.   <mat-card-content>  
  11.     <form [formGroup]="employeeForm"(ngSubmit)="onFormSubmit(employeeForm.value)">  
  12.             <table>  
  13.               <tr>  
  14.                 <td class="tbl1">  
  15.                   <mat-form-field class="demo-full-width">  
  16.                     <input formControlName="EmpName" matTooltip="Enter Employee Name" matInput placeholder="Employee Name">  
  17.                   </mat-form-field>  
  18.                   <mat-error>  
  19.                     <span *ngIf="!employeeForm.get('EmpName').value && employeeForm.get('EmpName').touched"></span>  
  20.                   </mat-error>  
  21.                 </td>  
  22.                 <td class="tbl1">  
  23.                   <mat-form-field class="demo-full-width">  
  24.                     <input matInput [matDatepicker]="picker"matTooltip="Enter Date Of Birth" formControlName="DateOfBirth"placeholder="Choose Date Of Birth">  
  25.                     <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>  
  26.                     <mat-datepicker #picker></mat-datepicker>  
  27.                   </mat-form-field>  
  28.                   <mat-error>  
  29.                     <span *ngIf="!employeeForm.get('DateOfBirth').value && employeeForm.get('DateOfBirth').touched"></span>  
  30.                   </mat-error>  
  31.                 </td>  
  32.                 <td class="tbl1">  
  33.                   <mat-form-field class="demo-full-width">  
  34.                     <input formControlName="EmailId" matTooltip="Enter EmailId" matInput placeholder="EmailId">  
  35.                   </mat-form-field>  
  36.                   <mat-error>  
  37.                     <span *ngIf="!employeeForm.get('EmailId').value && employeeForm.get('EmailId').touched"></span>  
  38.                   </mat-error>  
  39.                 </td>  
  40.               </tr>  
  41.               <tr>  
  42.                 <td class="tbl1">  
  43.                   <span>Gender</span>  
  44.                   <br><br>  
  45.                   <mat-radio-group matTooltip="Enter Gender"formControlName="Gender">  
  46.                       <mat-radio-button value="0">Male</mat-radio-button>    
  47.                       <mat-radio-button value="1">Female</mat-radio-button>  
  48.                     </mat-radio-group>  
  49.                   <mat-error>  
  50.                     <span *ngIf="!employeeForm.get('Gender').value && employeeForm.get('Gender').touched"></span>  
  51.                   </mat-error>  
  52.                 </td>  
  53.                 <td class="tbl1">  
  54.                   <mat-form-field class="demo-full-width">  
  55.                     <input matTooltip="Enter Address"formControlName="Address" matInput placeholder="Address">  
  56.                   </mat-form-field>  
  57.                   <mat-error>  
  58.                     <span *ngIf="!employeeForm.get('Address').value && employeeForm.get('Address').touched"></span>  
  59.                   </mat-error>  
  60.                 </td>  
  61.                 <td class="tbl1">  
  62.                   <mat-form-field class="demo-full-width">  
  63.                     <input formControlName="PinCode" matTooltip="Enter Pine Code" matInput placeholder="PinCode">  
  64.                   </mat-form-field>  
  65.                   <mat-error>  
  66.                     <span *ngIf="!employeeForm.get('PinCode').value && employeeForm.get('PinCode').touched"></span>  
  67.                   </mat-error>  
  68.                 </td>  
  69.               </tr>  
  70.               <tr>  
  71.                 <td></td>  
  72.                 <td  class="content-center">  
  73.                   <button type="submit" mat-raised-button color="accent"matTooltip="Click Submit Button"[disabled]="!employeeForm.valid">Submit</button>      
  74.                   <button type="reset" mat-raised-button color="accent"matTooltip="Click Reset Button" (click)="resetForm()">Reset</button>  
  75.                 </td>  
  76.                 <td>  
  77.                   <p *ngIf="dataSaved" style="color:rgb(0, 128, 0);font-size:20px;font-weight:bold" Class="success" align="left">  
  78.                     {{massage}}  
  79.                   </p>  
  80.                 </td>  
  81.               </tr>  
  82.             </table>  
  83. <br><br>  
  84.       <table class="table" >  
  85.           <tr ngclass="btn-primary">  
  86.             <th class="tbl2">Employee Name</th>  
  87.             <th class="tbl2">Date Of Birth</th>  
  88.             <th class="tbl2">Email Id</th>  
  89.             <th class="tbl2">Gender</th>  
  90.             <th class="tbl2">Address</th>  
  91.             <th class="tbl2">Pine Code</th>  
  92.             <th class="tbl2">Edit</th>  
  93.             <th class="tbl2">Delete</th>  
  94.           </tr>  
  95.           <tr *ngFor="let employee of allEmployees | async">  
  96.             <td class="tbl2">{{employee.EmpName}}</td>  
  97.             <td class="tbl2">{{employee.DateOfBirth | date }}</td>  
  98.             <td class="tbl2">{{employee.EmailId}}</td>  
  99.             <td class="tbl2">{{employee.Gender ==0? 'Male' : 'Female'}}</td>  
  100.             <td class="tbl2">{{employee.Address}}</td>  
  101.             <td class="tbl2">{{employee.PinCode}}</td>  
  102.             <td class="tbl2">  
  103.               <button type="button" class="btn btn-info"matTooltip="Click Edit Button"(click)="loadEmployeeToEdit(employee.EmpId)">Edit</button>  
  104.             </td>  
  105.             <td class="tbl2">  
  106.               <button type="button" class="btn btn-danger"matTooltip="Click Delete Button"(click)="deleteEmployee(employee.EmpId)">Delete</button>  
  107.             </td>  
  108.           </tr>  
  109.   
  110.         </table>  
  111.     </form>  
  112.   </mat-card-content>  
  113. </mat-card>  
  114. </div>  
Step 9
 
Open app.component.html and write the below code.
  1. <p>  
  2.   <app-employee></app-employee>  
  3. </p>  
Step 10
 
Open employee.component.ts file and write the below code.
  1. import { Component, OnInit } from '@angular/core';  
  2. import { FormBuilder, Validators } from '@angular/forms';  
  3. import { Observable } from 'rxjs';  
  4. import { EmployeeService } from '../employee.service';  
  5. import { Employee } from '../employee';  
  6.   
  7. @Component({  
  8.   selector: 'app-employee',  
  9.   templateUrl: './employee.component.html',  
  10.   styleUrls: ['./employee.component.css']  
  11. })  
  12. export class EmployeeComponent implements OnInit {  
  13.   dataSaved = false;  
  14.   employeeForm: any;  
  15.   allEmployees: Observable<Employee[]>;  
  16.   employeeIdUpdate = null;  
  17.   massage = null;  
  18.   
  19.   constructor(private formbulider: FormBuilder, private employeeService:EmployeeService) { }  
  20.   
  21.   ngOnInit() {  
  22.     this.employeeForm = this.formbulider.group({  
  23.       EmpName: ['', [Validators.required]],  
  24.       DateOfBirth: ['', [Validators.required]],  
  25.       EmailId: ['', [Validators.required]],  
  26.       Gender: ['', [Validators.required]],  
  27.       Address: ['', [Validators.required]],  
  28.       PinCode: ['', [Validators.required]],  
  29.     });  
  30.     this.loadAllEmployees();  
  31.   }  
  32.   loadAllEmployees() {  
  33.     this.allEmployees = this.employeeService.getAllEmployee();  
  34.   }  
  35.   onFormSubmit() {  
  36.     this.dataSaved = false;  
  37.     const employee = this.employeeForm.value;  
  38.     this.CreateEmployee(employee);  
  39.     this.employeeForm.reset();  
  40.   }  
  41.   loadEmployeeToEdit(employeeId: string) {  
  42.     this.employeeService.getEmployeeById(employeeId).subscribe(employee=> {  
  43.       this.massage = null;  
  44.       this.dataSaved = false;  
  45.       this.employeeIdUpdate = employee.EmpId;  
  46.       this.employeeForm.controls['EmpName'].setValue(employee.EmpName);  
  47.      this.employeeForm.controls['DateOfBirth'].setValue(employee.DateOfBirth);  
  48.       this.employeeForm.controls['EmailId'].setValue(employee.EmailId);  
  49.       this.employeeForm.controls['Gender'].setValue(employee.Gender);  
  50.       this.employeeForm.controls['Address'].setValue(employee.Address);  
  51.       this.employeeForm.controls['PinCode'].setValue(employee.PinCode);  
  52.     });  
  53.   
  54.   }  
  55.   CreateEmployee(employee: Employee) {  
  56.     if (this.employeeIdUpdate == null) {  
  57.       this.employeeService.createEmployee(employee).subscribe(  
  58.         () => {  
  59.           this.dataSaved = true;  
  60.           this.massage = 'Record saved Successfully';  
  61.           this.loadAllEmployees();  
  62.           this.employeeIdUpdate = null;  
  63.           this.employeeForm.reset();  
  64.         }  
  65.       );  
  66.     } else {  
  67.       employee.EmpId = this.employeeIdUpdate;  
  68.       this.employeeService.updateEmployee(employee).subscribe(() => {  
  69.         this.dataSaved = true;  
  70.         this.massage = 'Record Updated Successfully';  
  71.         this.loadAllEmployees();  
  72.         this.employeeIdUpdate = null;  
  73.         this.employeeForm.reset();  
  74.       });  
  75.     }  
  76.   }   
  77.   deleteEmployee(employeeId: string) {  
  78.     if (confirm("Are you sure you want to delete this ?")) {   
  79.     this.employeeService.deleteEmployeeById(employeeId).subscribe(() => {  
  80.       this.dataSaved = true;  
  81.       this.massage = 'Record Deleted Succefully';  
  82.       this.loadAllEmployees();  
  83.       this.employeeIdUpdate = null;  
  84.       this.employeeForm.reset();  
  85.   
  86.     });  
  87.   }  
  88. }  
  89.   resetForm() {  
  90.     this.employeeForm.reset();  
  91.     this.massage = null;  
  92.     this.dataSaved = false;  
  93.   }  
  94. }  
Step 11. Run
  
Open TERMINAL and write the following command to run the program.
 
ng serve -o