我有一个带输入文本框的简单页面。文本框绑定到jquery ui autocomplete,它对服务器进行AJAX调用。我的服务器端代码是ASP.NET MVC站点。 与通过Internet找到的大多数示例相比,我唯一的区别是我的服务器端代码返回PartialView(html代码)作为结果而不是JSON 。我看到AJAX调用正在发生,我也看到了AJAX成功事件中的HTML响应。
我的问题是如何绑定此HTML数据以显示在自动完成功能中?
我到目前为止的代码是:
$("#quick_search_text&#34)。自动完成({ minLength:3, html:是的, autoFocus:true, 来源:功能(请求,响应){
$.ajax({
type: "POST",
url: "serversideurl",
data: "{ 'SearchTerm': '" + request.term + "', 'SearchCategory': '" + $("#quick_search_category").val() + "' }",
contentType: "application/json; charset=utf-8",
dataType: "html",
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
},
success: function (data) {
//THIS IS WHERE MY HTML IS RETURNED FROM SERVER SIDE
//HOW DO I BIND THIS TO JQUERY UI AUTOCOMPLETE
}
});
},
select: function (event, ui) {
},
response: function (event, ui) {
console.log(ui);
console.log(event);
}
});
答案 0 :(得分:1)
这有效: 1)在控制器中创建一个动作并设置RouteConfig以启动此动作
public class HomeController : Controller
{
public ActionResult Index20()
{
MyViewModel m = new MyViewModel();
return View(m);
}
创建没有任何类型母版页的视图
添加此视图模型:
public class MyViewModel
{
public string SourceCaseNumber { get; set; }
}
转到管理Nuget包或PM控制台并添加到MVC 5项目 - Tim Wilson的MVC 5模型的Typeahead.js
将添加的HtmlHelpers.cs的命名空间更改为System.Web.Mvc.Html并重建
添加此课程:
public class CasesNorm
{
public string SCN { get; set; }
}
将这些方法添加到您的控制器:
private List<Autocomplete> _AutocompleteSourceCaseNumber(string query)
{
List<Autocomplete> sourceCaseNumbers = new List<Autocomplete>();
try
{
//You will goto your Database for CasesNorm, but if will doit shorthand here
//var results = db.CasesNorms.Where(p => p.SourceCaseNumber.Contains(query)).
// GroupBy(item => new { SCN = item.SourceCaseNumber }).
// Select(group => new { SCN = group.Key.SCN }).
// OrderBy(item => item.SCN).
// Take(10).ToList(); //take 10 is important
CasesNorm c1 = new CasesNorm { SCN = "11111111"};
CasesNorm c2 = new CasesNorm { SCN = "22222222"};
IList<CasesNorm> aList = new List<CasesNorm>();
aList.Add(c1);
aList.Add(c2);
var results = aList;
foreach (var r in results)
{
// create objects
Autocomplete sourceCaseNumber = new Autocomplete();
sourceCaseNumber.Name = string.Format("{0}", r.SCN);
sourceCaseNumber.Id = Int32.Parse(r.SCN);
sourceCaseNumbers.Add(sourceCaseNumber);
}
}
catch (EntityCommandExecutionException eceex)
{
if (eceex.InnerException != null)
{
throw eceex.InnerException;
}
throw;
}
catch
{
throw;
}
return sourceCaseNumbers;
}
public ActionResult AutocompleteSourceCaseNumber(string query)
{
return Json(_AutocompleteSourceCaseNumber(query), JsonRequestBehavior.AllowGet);
}