user2802591
user2802591

Reputation: 71

Search data in table using ajax in ASP.net MVC

I want to display data in a table based on the search criteria in a textbox. I have implemented it without using Ajax but do not know how to call controller method using jquery and update table data. Please try to solve my problem. Thanks...

Index.cshtml

@model IEnumerable<MvcApplication4.Models.tbl_product>
@{
    Layout = null;
}

    <!DOCTYPE html>
<html>
<head>
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.js")" type="text/javascript"></script>
    <title>Index</title>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#Button1').click(function () {
                alert("button clicked");
                $.ajax({
                    type: 'POST',
                    contentType: "application/json; charset=utf-8",
                    url: 'Home/Index',
                    data: "{'searchString':'" + document.getElementById('searchString').value + "'}",
                    async: false,
                    Success: function (response) {
                        alert("Success");

                           window.location.reload();
                    },
                    error: function () { alert("error"); }
                });

            });
        });
    </script>
</head>
<body>
    @*  @using (@Html.BeginForm("Index", "Home"))
    {*@
    @Html.TextBox("searchString");
    <input type="button" value="filter" id="Button1" />
    @* }*@
    <table id="showData">
        @{Html.RenderPartial("SearchList");}
    </table>
</body>
</html>

SearchList.cshtml(Partial View)

@foreach (var item in Model)
{ 
<tr>
<td>@item.ProductName</td>
<td>@item.ProductId</td>
<td>@item.ProductDesc</td>
</tr>
}

HomeController.cs

 public class HomeController : Controller
    {
        //
        // GET: /Home/
        ProductEntities dbentity = new ProductEntities();
        public ActionResult Index()
        {
            return View(dbentity.tbl_product.ToList());
        }

        [HttpPost]
        public ActionResult Index(string searchString)
        {
            var query = dbentity.tbl_product.Where(c => c.ProductName.Contains(searchString));
            return View(query.ToList());
        }

   }

Upvotes: 1

Views: 14217

Answers (4)

Karthik Bammidi
Karthik Bammidi

Reputation: 1851

                $.ajax({
                    type: 'POST',
                    contentType: "application/json; charset=utf-8",
                    url: 'Home/Index',
                    data: JSON.stringify({'searchString':document.getElementById('searchString').value }),
                    async: false,
                    Success: function (response) {
                        alert("Success");
                        //append the data in between table tbody like,
                        $('table tbody').html(response);
                        //No window.location.reload(); It will cause page reload initial data will appear in grid.
                    },
                    error: function () { alert("error"); }
                });
                return false

Hope this helps.

Upvotes: 1

JotaBe
JotaBe

Reputation: 39004

I'm not going to give you the exact answer, but to help you to get it.

There are two steps:

First you must get sure the request is being done, and the response is being get on the browser.

To do so, you can

  • do it on your way: leave only the alert("Success"); and check it's being run.
  • better than that, open the browser's developer console (I prefer Chrome, but you can also use IE or FireFox + FireBug add-on) using F12. Set breakpoints and inspect variable values and code flow. See thit tutorial for Chrome developer tools.
  • set a breakpoint on the server action, and check it's executed

Second Once you're sure the firs part is working fine, use your succes function to replace the table content with the data received in the response. You can do it in several ways with jQuery. For example

$('#showData').html(response);

Again, you can execute this code and inspect the contents of response from the developer's console in your browser. This makes things eaiser when you're starting to use javascript.

(If your action generated the whole table, you could use jQuery's replaceWith which replaces the target, instead of its content. Don't use this for this case).

FINAL NOTE: please, remove this code window.location.reload();!!! This reloads the whole page with the current URL, so whatever thing you do in advance will be lost.

Upvotes: 0

Hadash
Hadash

Reputation: 228

$.ajax({
            url: '/ControllerName/ActionName',
            type: "POST",
            data: {criteria: 'criteria'},
            contentType: "application/json",
            success: function (data) {
            //Replace existing table with the new view (with the table).
            }
        });

//write ControllerName without the key controller.

Upvotes: 1

PM.
PM.

Reputation: 1721

Your ajax request should look like:

        $.ajax({
        url: '/<ControllerName>/<MethodName>',
        type: "POST",
        data: requestData,
        contentType: "application/json;charset=utf-8",
        success: function (data, textStatus, XMLHTTPRequest) {

            //Success callback handling
        },
        error: function (XMLHTTPRequest, textStatus, errorThrown) {
            //Error callback handling
        },
        cache: false //whether you want to cache the response or not.
    });

Upvotes: 0

Related Questions