簡體   English   中英

在MVC4中自動完成

[英]autocomplete in MVC4

有關在我的項目中使AutoComplete工作的問題。 我正在使用MVC4。 我使用Json部分正確地遵循了一切。 我不確定問題是在jQuery上還是在我的控制器上。 以下是代碼

public ActionResult Index()
    {
        EmployeeContext db = new EmployeeContext();
        return View(db.Employees);
    }
    [HttpPost]
    public ActionResult Index(string Search_Data)
    {
        EmployeeContext db = new EmployeeContext();
        List<Employee> employees;
        if (string.IsNullOrEmpty(Search_Data))
        {
            employees = db.Employees.ToList();
        }
        else
        {
            employees = db.Employees
                .Where(s => s.EmpName.StartsWith(Search_Data)).ToList();
        }
        return View(employees);
    }
    public JsonResult GetEmployees(string term)
    {
        EmployeeContext db = new EmployeeContext();
        List<string> employees = db.Employees.Where(s => s.EmpName.StartsWith(term))
            .Select(x => x.EmpName).ToList();
        return Json(employees, JsonRequestBehavior.AllowGet);
    }

我的index.cshtml中使用了以下腳本

    <link href="~/Content/jquery-ui-1.10.4.custom.min.css" rel="stylesheet" type="text/css"/>
<script src="~/Scripts/jquery-1.10.2.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-ui-1.10.4.custom.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(function () {
        $("#txtSearch").autocomplete({
            source: '@Url.Action("GetEmployees","Employee")',
            minLength: 1
        });
    });
</script>

問題是GetEmployees方法沒有得到命中,我能夠通過輸入字符串搜索數據,但自動完成功能不起作用。

看起來你錯過了一個重要的腳本文件:

不引人注目的Ajax

我多次為這個問題墮落了。 jQuery自動完成使用jQuery ajax函數,如果你包含Unobtrusive Ajax腳本,這只適用於MVC。

我解決了錯誤並將腳本放在另一個區域,所以

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/angular")
<script src="~/Scripts/MyApp.js"></script>
<script src="~/Scripts/jquery-ui-1.10.4.custom.min.js" type="text/javascript"></script>   
@RenderSection("scripts", required: false)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM