Sunday 20 November 2022

Select Insert Edit Update and Delete (CRUD) with DropDownList using jQuery Ajax in ASP.Net MVC

 View

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
@model IEnumerable<CRUD_jQuery_MVC.Customer>
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <table id="tblCustomers" class="table" cellpadding="0" cellspacing="0">
        <tr>
            <th>Customer Id</th>
            <th>Name</th>
            <th>Country</th>
            <th></th>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
        </tr>
        @foreach (Customer customer in Model)
        {
            <tr>
                <td class="CustomerId">
                    <span>@customer.CustomerId</span>
                </td>
                <td class="Name">
                    <span>@customer.Name</span>
                    <input type="text" value="@customer.Name" style="display:none" />
                </td>
                <td class="Country">
                    <span>@customer.Country</span>
                    @*<input type="text" value="@customer.Country" style="display:none" />*@
                    @Html.DropDownList("selection", new List<SelectListItem>()
                                                       {
                                                           new SelectListItem { Text="India", Value="1" },
                                                           new SelectListItem { Text="Australia", Value="2" },
                                                           new SelectListItem { Text="USA", Value="3" }
                                                       }, new { @style = "display:none;width:90px;height:25px;", @id = "ddlEditCountry" })
                </td>
                <td>
                    <a class="Edit" href="javascript:;">Edit</a>
                    <a class="Update" href="javascript:;" style="display:none">Update</a>
                    <a class="Cancel" href="javascript:;" style="display:none">Cancel</a>
                    <a class="Delete" href="javascript:;">Delete</a>
                </td>
            </tr>
        }
    </table>
    <table border="0" cellpadding="0" cellspacing="0">
        <tr>
            <td>
                Name<br />
                <input type="text" id="txtName" style="width:140px" />
            </td>
            <td>
                Country:<br />
                @*<input type="text" id="txtCountry" style="width:140px" />*@
                @Html.DropDownList("selection", new List<SelectListItem>()
                                                       {
                                                           new SelectListItem { Text="India", Value="1" },
                                                           new SelectListItem { Text="Australia", Value="2" },
                                                           new SelectListItem { Text="USA", Value="3" }
                                                       }, new { @style = "width:90px;height:25px;", @id = "ddlAddCountry" })
            </td>
            <td style="width: 200px">
                <br />
                <input type="button" id="btnAdd" value="Add" />
            </td>
        </tr>
    </table>
 
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
    <script type="text/javascript">
        $(function () {
            //Remove the dummy row if data present.
            if ($("#tblCustomers tr").length > 2) {
                $("#tblCustomers tr:eq(1)").remove();
            }
        });
        function AppendRow(row, customerId, name, country) {
            //Bind CustomerId.
            $(".CustomerId", row).find("span").html(customerId);
 
            //Bind Name.
            $(".Name", row).find("span").html(name);
            $(".Name", row).find("input").val(name);
 
            //Bind Country.
            $(".Country", row).find("span").html(country);
            $(".Country", row).find("input").val(country);
            $("#tblCustomers").append(row);
        };
 
        //Add event handler.
        $("body").on("click", "#btnAdd", function () {
            var txtName = $("#txtName");
            var ddlCountry = $("#ddlAddCountry").find("option:selected");
            $.ajax({
                type: "POST",
                url: "/Home/InsertCustomer",
                data: '{name: "' + txtName.val() + '", country: "' + ddlCountry.text() + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    var row = $("#tblCustomers tr:last-child").clone(true);
                    AppendRow(row, r.CustomerId, r.Name, r.Country);
                    txtName.val("");
                }
            });
        });
 
        //Edit event handler.
        $("body").on("click", "#tblCustomers .Edit", function () {
            var row = $(this).closest("tr");
            $("td", row).each(function () {
                if ($(this).find("input").length > 0 || $(this).find("select").length > 0) {
                    $(this).find("input").show();
                    $(this).find("select").show();
                    $(this).find("span").hide();
                }
            });
            row.find(".Update").show();
            row.find(".Cancel").show();
            row.find(".Delete").hide();
            $(this).hide();
        });
 
        //Update event handler.
        $("body").on("click", "#tblCustomers .Update", function () {
            var row = $(this).closest("tr");
            $("td", row).each(function () {
                if ($(this).find("input").length > 0) {
                    //debugger;
                    var span = $(this).find("span");
                    var input = $(this).find("input");
                    span.html(input.val());
                    span.show();
                    input.hide();
                }
                if ($(this).find("select").length > 0) {
                    //debugger
                    var span = $(this).find('span');
                    var select = $(this).find("select");
                    span.html($(this).find("select").find("option:selected").text());
                    select.hide();
                    span.show();
                }
            });
            row.find(".Edit").show();
            row.find(".Delete").show();
            row.find(".Cancel").hide();
            $(this).hide();
            var customer = {};
            customer.CustomerId = row.find(".CustomerId").find("span").html();
            customer.Name = row.find(".Name").find("span").html();
            customer.Country = row.find(".Country").find("option:selected").text();
            $.ajax({
                type: "POST",
                url: "/Home/UpdateCustomer",
                data: '{customer:' + JSON.stringify(customer) + '}',
                contentType: "application/json; charset=utf-8",
                dataType: "json"
            });
        });
 
        //Cancel event handler.
        $("body").on("click", "#tblCustomers .Cancel", function () {
            var row = $(this).closest("tr");
            $("td", row).each(function () {
                if ($(this).find("input").length > 0 || $(this).find("select").length > 0) {
                    var span = $(this).find("span");
                    var input = $(this).find("input");
                    var select = $(this).find("select");
                    input.val(span.html());
                    span.show();
                    input.hide();
                    select.hide();
                }
            });
            row.find(".Edit").show();
            row.find(".Delete").show();
            row.find(".Update").hide();
            $(this).hide();
        });
 
        //Delete event handler.
        $("body").on("click", "#tblCustomers .Delete", function () {
            if (confirm("Do you want to delete this row?")) {
                var row = $(this).closest("tr");
                var customerId = row.find("span").html();
                $.ajax({
                    type: "POST",
                    url: "/Home/DeleteCustomer",
                    data: '{customerId: ' + customerId + '}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        row.remove();
                    }
                });
            }
        });
    </script>
</body>
</html>

Controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        CustomersEntities entities =new CustomersEntities();
        return View(entities.Customers);
    }
 
    [HttpPost]
    public JsonResult InsertCustomer(Customer customer)
    {
        using (CustomersEntities entities =new CustomersEntities())
        {
            entities.Customers.Add(customer);
            entities.SaveChanges();
        }
 
        return Json(customer);
    }
 
    [HttpPost]
    public ActionResult UpdateCustomer(Customer customer)
    {
        using (CustomersEntities entities =new CustomersEntities())
        {
            Customer updatedCustomer = (from cin entities.Customers
                                        where c.CustomerId == customer.CustomerId
                                        select c).FirstOrDefault();
            updatedCustomer.Name = customer.Name;
            updatedCustomer.Country = customer.Country;
            entities.SaveChanges();
        }
 
        return new EmptyResult();
    }
 
    [HttpPost]
    public ActionResult DeleteCustomer(int customerId)
    {
        using (CustomersEntities entities =new CustomersEntities())
        {
            Customer customer = (from cin entities.Customers
                                    where c.CustomerId == customerId
                                    select c).FirstOrDefault();
            entities.Customers.Remove(customer);
            entities.SaveChanges();
        }
        return new EmptyResult();
    }
}

Screenshot

No comments:

Post a Comment