ceci bela

ceci bela

  • NA
  • 48
  • 7.4k

autocomplete - passing hidden primary key

Dec 16 2014 5:00 PM
-- my .cshtml --
@using (@Html.BeginForm())
{
@Html.TextBox("searchTerm",null, new { id = "txtSearch" })
<input type="submit" value="Search" />
}
<script src="~/Scripts/jquery-ui-1.11.2.custom/external/jquery/jquery.js"></script>
<script src="~/Scripts/jquery-ui-1.11.2.custom/jquery-ui.js"></script>
<script>
$("#txtSearch").autocomplete({
source: '@Url.Action("Getusers")'
});
</script>
 
-- controller --
[HttpGet]
public ActionResult Autocomplete()
{
return View(db.Table2.ToList());
}
[HttpPost]
public ActionResult Autocomplete(string searchTerm)
{
List<Table2> users;
if (string.IsNullOrEmpty(searchTerm))
{
users = db.Table2.ToList();
}
else
{
users = db.Table2.Where(x => x.userID.Contains(searchTerm)).ToList();
}
return View(users);
}
public JsonResult GetUsers(string term)
{ // Possible problem in the code below
var users = from cust in db.Table1.Where(c => c.LName.StartsWith(term)) select new {id = cust.UserID, value = cust.LName};
return Json(students, JsonRequestBehavior.AllowGet);
}
 
PROBLEM:
I want the users to search for the LastName and once he/she selects an item I want to populate the hidden field with the id(primary key) of that particular selection.
For example, the user types "Smith" in the search textbox. The system shows all the available "Smiths"...and when the user makes a selection pass the primary key(eg 10) and not the text "smith" as it is doing now.
 
Thanks you 
 

Answers (6)