ASP.NET MVC 5 Partial View with Ajax Form

Nay hãy cùng nhau thực hiện thử AjaxForm trong ASP.NET MVC 5. Dùng xây dựng chức năng tìm kiếm, bạn có thể dùng xây dựng các chức năng khác như (insert,update,delete) điều có thể áp dụng được nhé
Chuẩn bị

  • Tạo project File->New project->choose APS.NET MVC5
  • Install Entity Framework để hổ trợ connect tới database và thực thi câu lệnh lấy dữ liệu
  • Thêm database đến Project: Click right App_Data->SQL serve database
  • Install Bootstrap để viết giao diện
  • Install Unobtrusive Ajax Script đến project, để có thể sử dụng Ajax Form

Sau khi cài đặt xong các bước trên, nếu chưa hình dung được cách cài đặt bạn có thể xem lại các bài viết sau đây:

Okay, hãy mở file điều kiển Controller của bạn lên và thiết lập nó, ở đây của mình là file HomeController.cs trong Controllers/HomeController.cs

 public ActionResult AjaxSearch(string q)
        {
            var data = getUser(q);
            return PartialView("_AjaxSearch",data);
        }

        public List<User> getUser(string query)
        {
            return _db.Users.Where(s => s.LastName.Contains(query)).ToList();
        }

AjaxSearch(string q): mình nhận vào một chuỗi tìm kiếm từ form, sao đó ta tìm kiếm trong table Users, sau đó return dữ liệu ra PartialView _AjaxSearch.cshtml
Hãy tạo file _AjaxSearch.cshtml trong thư mục Views/Home/_AjaxSearch.cshtml

@model IEnumerable<FormValidation.Models.User>
@{ int STT = 0;}
@foreach(var m in Model) {
    STT++;
    <tr>
        <td>@STT</td>
        <td>@m.FirstName</td>
        <td>@m.LastName</td>
        <td>@m.FullName()</td>
        <td>@m.Email</td>
        <td>@Html.ActionLink("Modify", "Edit", "Home", new { id = m.idUser, @class = "badge badge-warning" })</td>
        <td>@Html.ActionLink("Removed", "Delete", "Home", new { id = m.idUser, @class = "badge badge-danger" })</td>
    </tr>
}

Trong file bên trên nhận dữ liệu từ Controller return về, sau đó hiển thị dữ liệu ra khung nhìn. Ok giờ ta hãy tạo một file Index.cshtml trong Views/Home/Index.cshtml để thiết lập form tìm kiếm

@model FormValidation.Models.User

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_LayoutPage1.cshtml";
}
<div class="container">
    <div class="row justify-content-md-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">
                    <div class="card-title">
                        Ajax Search User
                    </div>
                </div>
                <div class="card-body">
                    @using (Ajax.BeginForm("AjaxSearch", "Home", new AjaxOptions
                    {
                        InsertionMode = InsertionMode.Replace,
                        HttpMethod = "GET",
                        OnFailure = "searchFailed",
                        LoadingElementId = "ajax-loader",
                        UpdateTargetId = "searchResult",

                    }))
                    {
                        <input type="text" name="q" class="form-control" />
                        <input type="submit" value="search" class="btn btn-success" />
                        <img id="ajax-loader"
                             src="@Url.Content("~/Images/ajax-loader.gif")"
                             style="display:none" />
                    }
                </div>
            </div>
			<div class="ajax-loader"></div>
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th colspan="7">List Users</th>
                    </tr>
                    <tr>
                        <th>STT</th>
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>Full Name</th>
                        <th>Email</th>
                        <th>Edit</th>
                        <th>Delete</th>
                    </tr>
                </thead>
                <tbody id="searchResult">
					
                </tbody>
            </table>

        </div>
    </div>
</div>
@section Scripts {
    <script>
        $(document).ready(function () {
            function searchFailed() {
                $("#searchResult").html("Sorry, there was a problem with the search.");
            }
        });
    </script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
}
  • LoadingElementId: id="ajax-loader" hiễn thị img loader
  • UpdateTargetId: id="searchResult" dùng để load dữ liệu trả về
  • HttpMethod: phương thức (GET,POST)
  • InsertionMode: có 3 tham số("InsertAfter", "InsertBefore", "Replace") dùng chỉ định cách chèn phần tử trả về

Demo:

ASP.NET MVC 5 Partial View with Ajax Form

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)