1

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());
        }

   }

4 Answers 4

1
$.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.

Sign up to request clarification or add additional context in comments.

1 Comment

I have made changes but ajax part is not executing, i have edited my above code...
1
                $.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.

Comments

0

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.
    });

1 Comment

I have changed the above code and implemented ajax but it is not working and table is not updated.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.