user2802591
user2802591

Reputation: 71

Data not loaded in table using ajax in ASP.net mvc

I want to retrieve data in an html table using Ajax in ASP.net mvc but the success part is not executing and do not know how to show returned data in a table using Ajax. Please suggest any method to solve this issue. 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>

    @Html.TextBox("searchString");
    <input type="button" value="filter" id="Button1" />
    <table id="showData">
        @{Html.RenderPartial("SearchList");}
    </table>
</body>
</html>

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

SearchList.cshtml

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

Upvotes: 0

Views: 1524

Answers (1)

Satpal
Satpal

Reputation: 133403

  1. Its success not Success
  2. You need to return Partial View
  3. You need to updated table HTML with returned partial view

Change You code as

success: function (response) {
    alert("Success");
    $('#showData').html(response)
},

Controller Code

 return PartialView("SearchList", query.ToList());

If you are not supplying ViewName, by convention It will use ActionName as view name. thus pass SearchList as ViewName

EDIT:

Also, You need to pass model to render partial

@{Html.RenderPartial("SearchList", Model);}

Upvotes: 1

Related Questions