quarta-feira, 25 de setembro de 2013

Autocomplete - MVC3, RAZOR, LINQ, JQuery

Hi!
This infernal autocomplete took me two days, but I finally made it. Territories is an entity from Northwind schema.

DAO


        public IQueryable<string> getTerritoryDescription(string searchstring)
        {

            NorthwindDataContext lObjND = new NorthwindDataContext();
            var suggestions = from p in lObjND.Territories select p.TerritoryDescription;
            var namelist = suggestions.Where(n => n.ToLower().StartsWith(searchstring.ToLower()));
            return namelist;
        }

CONTROLLER


        public JsonResult AutoCompleteSuggestions(string term)
        {
            var suggestions = (new TerritoriesDAO()).getTerritoryDescription(term);
            var namelist = suggestions.Where(n => n.ToLower().StartsWith(term.ToLower()));
            return Json(namelist, JsonRequestBehavior.AllowGet);
        }

Attention: if you try to use another parameter name instead of term, it will not work. Something like (string searchstring) doesn't work.

VIEW

<script src="../../Scripts/jquery-ui-1.8.11.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.11.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>

<script type="text/javascript">
    $(function () {
        $("#SearchString").autocomplete({
            source: "/Territories/AutocompleteSuggestions",
            minLength: 1  });
    });
</script>

.
.
@using (Html.BeginForm())
{
    <p>
        Find by name: @Html.TextBox("SearchString") 
        <input type="submit" value="Search" /></p>
}


And that's it!

Nenhum comentário:

Postar um comentário