【问题标题】:autocomplete in MVC4MVC4 中的自动完成
【发布时间】:2016-02-15 06:32:34
【问题描述】:

在我的项目中使用 AutoComplete 时遇到问题。我正在使用 MVC4。我已经使用 Json 部分正确地跟踪了所有内容。我不确定问题出在 jQuery 上还是在我的 Controller 上。 以下是代码

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 方法没有命中,我可以通过输入字符串来搜索数据,但自动完成功能不起作用。

【问题讨论】:

  • 您是否在控制台中遇到了一些错误?
  • 不,我没有收到任何错误
  • 你的操作被调用了吗?

标签: javascript c#


【解决方案1】:

您似乎缺少一个重要的脚本文件:

Unobtrusive Ajax

我已经为这个问题堕落了很多次。 jQuery 自动完成功能使用 jQuery ajax 函数,并且仅在包含 Unobtrusive Ajax 脚本时才适用于 MVC。

【讨论】:

  • 我包含了不显眼的 Ajax 脚本,但没有用,自动搜索仍然不起作用
【解决方案2】:

我解决了错误并将脚本放在另一个区域,所以

@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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-20
    • 2012-06-12
    相关资源
    最近更新 更多