ASP.NET MVC 5 Partial View with Ajax Form
Tags: csharp, webdev, tutorial, beginners
Published: 2019-11-02 07:53:28

Today, I share a example simple from Partial View with Ajax Form in ASP.NET MVC 5, everyone can applied build (insert,update or delete) with Ajax Form

Preparation
+ Create a project: **File->New project->choose ASP.NET MVC 5**
+ **Install Entity Framework** to support connect database and query excute command to table in database
+ Add database to project: click right **App_Data->SQL serve database**
+ **Install Bootstrap** to write the interface
+ **Install Unobtrusive Ajax Script** to Project, to support use Ajax Form

After installing the above steps, if you have not figued how to install, you can review the following articles
+ [ASP.NET MVC 5 Hello World](https://dev.to/skipperhoa/asp-net-mvc-5-helllo-world-1o55)
+ [Install Bootstrap và Entity Framework in ASP.NET MVC 5](https://dev.to/skipperhoa/asp-net-mvc-5-install-bootstrap-2d3a)
+ [ASP.NET MVC 5 Using DBContext Connect Database](https://dev.to/skipperhoa/asp-net-mvc-5-using-dbcontext-connect-database-3846)

Okay, open your Controller file and set it up, here is your HomeController.cs file in Controllers directory 
```csharp
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):** use received a search string from the form, after then query to table Users
Let's create Partial _AjaxSearch.cshtml file in **Views/Home/_AjaxSearch.cshtml** directory
```csharp
@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>
}
```
In the above _AjaxSearch.cshtml file,return data recieved from Controller, aften then display to view

Okay, continue! let's create Index.cshtml file in **Views/Home/Index.cshtml** directory, we set form search

```csharp
@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" displays img loader
+ **UpdateTargetId:** id = "searchResult" is used to load the returned data
+ **HttpMethod:** method (GET, POST)
+ **InsertionMode:** has 3 parameters ("InsertAfter", "InsertBefore", "Replace") that specify how to insert the returned element.

Demo:
![ASP.NET MVC 5 Partial View with Ajax Form - hoanguyenit.com](https://thepracticaldev.s3.amazonaws.com/i/n7xdcmrz80yihxpjmxor.png)

The article: [ASP.NET MVC 5 Partial View with Ajax Form](https://hoanguyenit.com/aspnet-mvc5-partial-view-with-ajax-form.html)