Erik Sellberg
Erik Sellberg

Reputation: 511

How to search using Ajax in asp.net MVC

I am trying to refresh a table without loading the entire page using Ajax. When I call the PartialViewResult it doesn't fetch the string from the textbox and does a "empty search" and returns all the values in the table instead of the specific that I am searching for.

How do I fetch the string inside the html textbox and use it in the PartialVewResult to get only the results that I search for?

Html code (LogLayout.cshtml)

    @using (Ajax.BeginForm("LogPartialView", "LogModelsController",
                new AjaxOptions
                {
                    HttpMethod = "POST",
                    InsertionMode = InsertionMode.Replace,
                    UpdateTargetId = "divLogs"
                }))
                                {
                                    <p>
                                        <b>Message:</b> @Html.TextBox("SearchString")
                                        <input type="submit" id="submit" name="submit" value="Search" />

                                    </p>
                                }<div id="divLogs">
                                    @RenderBody()
                                    @Html.Raw(ViewBag.Data)
                                </div>

Controller (LogModelsController)

 public PartialViewResult LogPartialView(string searchString, string currentFilter, int? page, string sortOrder)
        {
            ViewBag.CurrentSort = sortOrder;

            string myID = "0";
            if (Session["myID"] != null)
            {
                myID = Session["myID"].ToString();
            }
            int testID;
            try
            {
                testID = Convert.ToInt32(myID);
            }
            catch (FormatException ex)
            {
                throw new FormatException("FormatException error in LogModelsController", ex);
            }

            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;
            //Linq code that gets data from the database
            var message = (from log in db.Log
                           where log.customerId == testID
                           select log);

            if (!String.IsNullOrEmpty(searchString))
            {
                message = message.Where(s => s.message.Contains(searchString));
            }

            //PageSize displays the maximum number of rows on each page
            int pageSize = 10;
            int pageNumber = (page ?? 1);

            return PartialView("_LogPartialLayout", message.OrderByDescending(i => i.timeStamp).ToPagedList(pageNumber, pageSize));
        }
    }
}

The Partial Layout (_LogPartialLayout.cshtml)

@model PagedList.IPagedList<ASDMVC.Models.LogModel>
@using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />

<table class="table">
    <tr>
        <th>
            @Html.ActionLink("message", "Index", new { sortOrder = ViewBag.NameSortParm, currentFilter = ViewBag.CurrentFilter })

        </th>
        <th>
            @Html.ActionLink("timestamp", "Index", new { sortOrder = ViewBag.NameSortParm, currentFilter = ViewBag.CurrentFilter })
        </th>
        <th>
            @Html.ActionLink("level", "Index", new { sortOrder = ViewBag.NameSortParm, currentFilter = ViewBag.CurrentFilter })
        </th>

    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.message)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.timeStamp)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.level)
            </td>
        </tr>
    }
</table>
Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount

@Html.PagedListPager(Model, page => Url.Action("Index",
    new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))

Upvotes: 1

Views: 7190

Answers (1)

Erik Sellberg
Erik Sellberg

Reputation: 511

I found a solution!:)

I had to add a new id for my table:

 @using (Ajax.BeginForm("LogPartialView", "LogModelsController",
          new AjaxOptions
          {
          HttpMethod = "POST",
          InsertionMode = InsertionMode.Replace,
          UpdateTargetId = "divLogs"
      }, new
      {
         id = "NewTableId"
       )){
     <p>
       <b>Message:</b> @Html.TextArea("SearchString")
       <input type="submit" id="submit" name="submit" value="Search" />
     </p>
     }<div id="divLogs">
     @RenderBody()
     @Html.Raw(ViewBag.Data)
     </div>

Upvotes: 1

Related Questions