There are many common examples. This article is just my work record.
Front-end page:
@{
ViewBag. Title = "Homepage ";
}
@ Section Header
{
<Script type = "text/javascript">
$ (Document). ready (function (){
$ ("# Keyword"). autocomplete ({
Source: function (request, response ){
$. Ajax ({
Url: "@ Url. Action (" Search "," Home ")", // The Action to query
Type: "POST", // Post submit
DataType: "json", // json format data. The default value is text.
Data: {keyword: request. term}, // parameter. Why? Please advise
// Data: {keyword: $ ("# keyword"). val ()}, you can also
Success: function (data ){
Response ($. map (data, function (item ){
Return {label: item. text, value: item. value}; // assign the returned jsonresult attribute to autocomplete item
}));
}
});
},
Focus: function (event, ui ){
$ ('# Keyword'). val (ui. item. label); // select the text of the item
Return false;
},
Select: function (event, ui ){
$ ('# Keyword'). val (ui. item. label); // select the text of the item
$ ('# Txtselectvalue'). val (ui. item. value); // The value of the selected item
Return false;
}
});
});
</Script>
}
Keywords:
@ Html. TextBox ("keyword ","")
@ Html. Hidden ("txtSelectValue") // intelligently queries the selected value
Action Code:
// GET:/Home/Index
// POST:/Home/Search
Public ActionResult Index ()
{
Return View ();
}
[HttpPost]
Public ActionResult Search (string keyword)
{
// Query by keyword and return a set of objects in json format
Method 1: loop
List <object> items = new List <objects> ();
Var item = new {text = "", value = ""}
Items. Add (item );
Method 2: directly add the object using linq to Entity
Var dataList = organService. AddDataList (); // obtain the data list
Items. AddRange (dataList. Select (o => new
{
Text = o. NAME,
Value = o. CODE. ToString ()
}));
//---------------------------------------
Return Json (items, JsonRequestBehavior. AllowGet );
}
From: BirchLee's personal blog