Cấp bậc tác giả:

DOTNET

Thao tác CRUD trong ASP.NET MVC bằng AJAX và Bootstrap có sử dụng JsonResult

Được viết bởi webmaster ngày 19/03/2023 lúc 04:46 PM
Để thực hiện thao tác CRUD trong ASP.NET MVC bằng AJAX và Bootstrap, ta cần thực hiện các bước sau
  • 0
  • 2103

Thao tác CRUD trong ASP.NET MVC bằng AJAX và Bootstrap có sử dụng JsonResult

Để thực hiện thao tác CRUD trong ASP.NET MVC bằng AJAX và Bootstrap, ta cần thực hiện các bước sau:
  1. Tạo một Model và một DbContext để thao tác với cơ sở dữ liệu.
  2. Tạo một Controller để quản lý các thao tác CRUD trên Model.
  3. Tạo một View để hiển thị dữ liệu và cho phép người dùng thực hiện các thao tác CRUD.
  4. Cài đặt thư viện Bootstrap và jQuery.
  5. Sử dụng AJAX để thực hiện các thao tác CRUD mà không cần phải tải lại trang.
Dưới đây là một mẫu đơn giản về thao tác CRUD trong ASP.NET MVC bằng AJAX và Bootstrap:

1. Tạo Model và DbContext
public class Employee  
{  
    public int EmployeeID { get; set; }  
    public string Name { get; set; }       
    public int Age { get; set; }     
    public string State { get; set; }      
    public string Country { get; set; }  
}  

public class ApplicationDbContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }
}
2. Tạo Controller
public class EmployeeController : Controller  
{  
    EmployeeDB db = new EmployeeDB();  
    // GET: Home  
    public ActionResult Index()  
    {  
        return View();  
    }  
[HttpPost]
public JsonResult Create(Employee employee)
{
    try
    {
        if (ModelState.IsValid)
        {
            db.Employees.Add(employee);
            db.SaveChanges();
            return Json(new { success = true });
        }
    }
    catch (Exception ex)
    {
        return Json(new { success = false, message = ex.Message });
    }
    return Json(new { success = false });
}

}  
3. Tạo View Employee
Trong đó, chúng ta sử dụng phương thức JsonResult để trả về kết quả. Nếu tạo sản phẩm thành công, chúng ta trả về một đối tượng JSON với thuộc tính success = true. Nếu có lỗi xảy ra, chúng ta trả về một đối tượng JSON khác với thuộc tính success = false và một thông báo lỗi.
Trong JavaScript, chúng ta có thể sử dụng phương thức done() để xử lý kết quả trả về từ phương thức AJAX. Ví dụ:
// Save product
$(document).on('click', '#btn-save', function () {
    var form = $('#form-employee');
    var url = form.attr('action');
    var data = form.serialize();

    $.post(url, data)
        .done(function (response) {
            if (response.success) {
                $('#modal-form').modal('hide');
                location.reload();
            } else {
                alert(response.message);
            }
        })
        .fail(function (error) {
            console.log(error);
        });
});
Trong đó, chúng ta kiểm tra thuộc tính success của đối tượng JSON trả về. Nếu thành công, chúng ta ẩn modal và tải lại trang. Nếu không thành công, chúng ta hiển thị thông báo lỗi.
Đây là một ví dụ về file View cho trang hiển thị danh sách sản phẩm, sử dụng AJAX và Bootstrap để thực hiện các thao tác CRUD:
@model IEnumerable<Employee>

@{
    ViewBag.Title = "Employees";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>@ViewBag.Title</h2>

<div class="text-center">
    <button class="btn btn-success create">Create</button>
</div>

<table class="table">
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>State</th>
            <th>Country</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>@Html.DisplayFor(modelItem => item.Name)</td>
                <td>@Html.DisplayFor(modelItem => item.Age)</td>
                <td>@Html.DisplayFor(modelItem => item.State)</td>
                <td>@Html.DisplayFor(modelItem => item.Country)</td>
                <td>
                    <button class="btn btn-info edit" data-id="@item.Id">Edit</button>
                    <button class="btn btn-danger delete" data-id="@item.Id">Delete</button>
                </td>
            </tr>
        }
    </tbody>
</table>

<div id="modal-form" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title"></h4>
            </div>
            <div class="modal-body">
                <form id="form-product" method="post" action="#">
                    <div class="form-group">
                        <label for="Name">Name</label>
                        <input type="text" class="form-control" id="Name" name="Name" placeholder="Enter name" required>
                    </div>
                    <div class="form-group">
                        <label for="Age">Age</label>
                        <textarea class="form-control" id="Age" name="Description" placeholder="Enter Age"></textarea>
                    </div>
                    <div class="form-group">
                        <label for="State">State</label>
                        <input type="number" class="form-control" id="State" name="Price" placeholder="Enter state" required>
                    </div>
                    <div class="form-group">
                        <label for="Country">Country</label>
                        <input type="number" class="form-control" id="Country" name="Quantity" placeholder="Enter country" required>
                    </div>
                    <input type="hidden" id="Id" name="Id">
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="btn-save">Save</button>
            </div>
        </div>
    </div>
</div>

@section Scripts {
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
    <script>
        $(document).ready(function () {
            // Create product
            $(document).on('click', '.create', function () {
                $('#modal-form').modal('show');
                $('.modal-title').text('Create Employee');
                $('#btn-save').attr('data-action', '@Url.Action("Create", "Employee")');
                $('#form-product').trigger('reset');
            });

            // Edit product
            $(document).on('click', '.edit', function () {
                var id = $(this).data('id');
                $.get('@Url.Action("Edit", "Employee")', { id: id })
                    .done(function (response) {
                        if (response.success) {
                            $('#modal-form').modal('show');
                            $('.modal-title').text('Edit Employee');
                            $('#btn-save').attr('data-action', '@Url.Action("Edit", "Employee")');
                            $('#Id').val(response.data.Id);
                            $('#Name').val(response.data.Name);
                            $('#Age').val(response.data.Age);
                            $('#State').val(response.data.State);
                            $('#Country').val(response.data.Country);
                        } else {
                            alert(response.message);
                        }
                    })
                    .fail(function (error) {
                        console.log(error);
                    });
            });

            // Delete product
            $(document).on('click', '.delete', function () {
                var id = $(this).data('id');
                if (confirm('Are you sure to delete this employee?')) {
                    $.post('@Url.Action("Delete", "Employee")', { id:id })
.done(function (response) {
if (response.success) {
location.reload();
} else {
alert(response.message);
}
})
.fail(function (error) {
console.log(error);
});
}
});

        // Save product
        $(document).on('click', '#btn-save', function () {
            var form = $('#form-product');
            $.post($(this).attr('data-action'), form.serialize())
                .done(function (response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        alert(response.message);
                    }
                })
                .fail(function (error) {
                    console.log(error);
                });
        });
    });
</script>
}
Trong file này, chúng ta có một danh sách nhân viên được hiển thị bằng một bảng HTML. Mỗi hàng bảng đại diện cho một nhân viên và có chứa các thông tin như tên, tuổi, tỉnh và quốc gia. Bên cạnh đó, chúng ta còn có các nút để thêm, sửa và xóa nhân viên.

Khi người dùng nhấp vào các nút này, một modal form sẽ được hiển thị để cho phép thực hiện các thao tác CRUD (Create, Read, Update, Delete) trên sản phẩm. Các thao tác này được thực hiện bằng cách sử dụng JavaScript và Ajax để tương tác với API của ứng dụng.

4. Cài đặt thư viện Bootstrap và jQuery
Thêm các đoạn mã sau vào file BundleConfig.cs để cài đặt thư viện Bootstrap và jQuery:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
    "~/Scripts/jquery-{version}.js"));

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
    "~/Scripts/jquery.validate*"));

bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
    "~/Scripts/modernizr-*"));

bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
    "~/Scripts/bootstrap.js",
    "~/Scripts/respond.js"));

bundles.Add(new StyleBundle("~/Content/css").Include(
    "~/Content/bootstrap.css",
    "~/Content/site.css"));
5. Sử dụng AJAX để thực hiện các thao tác CRUD
Thêm các đoạn mã sau vào đầu file View để sử dụng AJAX:
@section scripts {
    <script>
        $(document).ready(function () {

            // Show modal form for create or edit
            $(document).on('click', '.create, .edit', function () {
                var id = $(this).data('id');
                var url = id ? '/Products/Edit/' + id : '/Products/Create';

                $.get(url, function (data) {
                    $('#modal-form').find('.modal-body').html(data);
                    $('#modal-form').modal('show');
                });
            });

            // Save product
            $(document).on('click', '#btn-save', function () {
                var form = $('#form-product');
                var url = form.attr('action');
                var data = form.serialize();

                $.post(url, data)
                    .done(function (response) {
                        $('#modal-form').modal('hide');
                        location.reload();
                    })
                    .fail(function (error) {
                        console.log(error);
                    });
            });

            // Show modal form for delete
            $(document).on('click', '.delete', function () {
                var id = $(this).data('id');
                $('#delete-id').val(id);
                $('#modal-delete').modal('show');
            });

            // Delete product
            $(document).on('click', '#btn-delete', function () {
                var id = $('#delete-id').val();
                var url = '/Products/Delete/' + id;

                $.post(url)
                    .done(function (response) {
                        $('#modal-delete').modal('hide');
                        location.reload();
                    })
                    .fail(function (error) {
                        console.log(error);
                    });
            });

        });
    </script>
}
Trên đây là một ví dụ về cách sử dụng JavaScript và Ajax để tạo một ứng dụng web đơn giản. Tuy nhiên, để phát triển một ứng dụng web thực sự, chúng ta cần học nhiều hơn về các công nghệ và kỹ thuật khác nhau, nhưng điều đó có thể đòi hỏi nhiều thời gian và nỗ lực.

Nguồn bài viết: DOTNET.VN

BÌNH LUẬN BÀI VIẾT

Bài viết mới nhất

LIKE BOX

Bài viết được xem nhiều nhất

HỌC HTML