Pulse7
7/16/2017 - 1:46 PM

Full ajax search example with highlighting

Full ajax search example with highlighting

$(function () {
    var ajaxFormSubmit = function () {
        var $form = $(this);
        var options = {
            url: $form.attr("action"),
            method: $form.attr("method"),
            data: $form.serialize()
        };
        $.ajax(options).done(function (data) {
            var $target = $($form.attr("data-otf-target"));
            var $newHtml = $(data);

            $target.replaceWith($newHtml);
            $newHtml.effect("highlight");
        })
        return false;
    };

    var submitAutocomplete = function (event,ui) {
        $input = $(this);
        $input.val(ui.item.label);

        var $form = $input.parents("form:first");
        $form.submit();
    }

    var createAutocomplete = function () {
        $input = $(this);
        var options = {
            source: $input.attr("data-otf-autocomplete"),
            select: submitAutocomplete
        }
        $input.autocomplete(options);
    }

    $("form[data-otf-ajax='true']").submit(ajaxFormSubmit);
    $("input[data-otf-autocomplete]").each(createAutocomplete);
})
@{
    ViewBag.Title = "Home Page";
}
@using WebApplication1.Models;
@model IEnumerable<RestaurantViewModel>

<div id="d" class="jumbotron green" >
        <form method="get" action=@Url.Action("Index") data-otf-ajax="true" data-otf-target="#restaurantList" >
            <input type="text" name="search" value="" data-otf-autocomplete=@Url.Action("Autocomplete") />
            <input type="submit" value="Search by name" />
        </form>
    </div>

@Html.Partial("_Restaurants",Model)
public ActionResult Autocomplete(string term)
        {
            var model = db.Restaurants
                .Where(r => r.Name.StartsWith(term))
                .Take(10)
                .Select(r => new { label = r.Name });
            return Json(model, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Index(string search="")
        {
            var model = db.Restaurants
                    .Where(r => r.Name.Contains(search))
                    .OrderByDescending(r => r.Reviews.Average(rr => rr.Rating))
                    .Select(r => new RestaurantViewModel { ID = r.ID, Name = r.Name, Country = r.Country, City = r.City, NumReviews = r.Reviews.Count })
                    .Take(10);
            if (Request.IsAjaxRequest())
            {
                return PartialView("_Restaurants",model);
            }
            else
            {
                return View(model);
            }
        }