I am making a text-box with drop down for auto-completing suggestion using jquery and ajax but the error I have found through debugging is that when the debug point comes to the given code it successfully moves to return statement and when comes second time on the same statement it gives an exception that "Keyword is null" (Keyword is the alphabet entered by the user in the textbox)
var result = (from a in objGameList where
a.GameName.ToLower().StartsWith(keyword.ToLower())
select new { a.GameName });
Here is the code:
Index.cs
<script type="text/javascript">
$(document).ready(function () {
$("#GameName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/Index",
type: "POST",
dataType: "json",
data: { keyword: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.GameName, value: item.GameName };
}))
},
error: function () {
alert('something went wrong !');
}
})
},
messages: {
noResults: "", results: ""
}
});
})
</script>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
<div>
@Html.EditorFor(model => model.GameName, new { htmlAttributes = new { @class = "form-control" } })
</div>
</div>
</div>
}
```
Controller.cs
[HttpPost]
public JsonResult Index(string keyword)
{
//This can be replaced with database call.
List<Games> objGameList = new List<Games>(){
new Games {Id=1,GameName="Cricket" },
new Games {Id=2,GameName="Football" },
new Games {Id=3,GameName="Chesh" },
new Games {Id=4,GameName="VallyBall" },
};
var result = (from a in objGameList
where a.GameName.ToLower().StartsWith(keyword.ToLower())
select new { a.GameName });
return Json(result);
}
Thanks in advance.
when comes second time on the same statement- what do You exacly mean by that? It hits breakpoint inside the controller for the second time without calling AJAX? Or You type and delete a letter, forcing autocomplete to send the same request and the second one does not have any data with it? Which version of the jQuery and jQuery UI are You using? I've used jQuery 1.12.4 and UI 1.12.1 to reproduce with no results.Modeldefinition in your View... the following is invalid:@Html.EditorFor(model => model.GameName