为什么我的自动完成控件没有调用?

时间:2012-03-20 10:04:47

标签: c# asp.net-mvc-3 jquery-ui razor autocomplete

我已按照此tutorial ...

我的控制器的方法“名称”永远不会被调用...

以下是代码:

查看

<script src="@Url.Content("~/Scripts/jquery.autocomplete.js")" type="text/javascript"> </script>
<link href="@Url.Content("~/Scripts/jquery.autocomplete.css")" rel="stylesheet" type="text/css" />

<script type="text/javascript">
$(document).ready(function () {
          $("#Name").autocomplete('@Url.Action("Name", "Reservation")', { minChars: 3   });//Never call... When I put a simple alert, it works !
});
</script>

<div class="editor-label">
    @Html.LabelFor(model => model.Customer.Name)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.Customer.Name)

</div>

控制器方法

public ActionResult Name(string q)
{
        var customers = (from c in db.Customers where c.Name.Contains(q) select c.Name).Distinct().Take(10);
        string content = string.Join<string>("\n", customers);
        return Content(content);
}

我迷路了......你能帮我找一下我做错了吗?提前谢谢......

最后他达到我控制器的方法!但他从不显示与输入文本对应的列表:(

更新16:04

enter image description here

1 个答案:

答案 0 :(得分:2)

由:

生成的输入的ID
@Html.EditorFor(model => model.Customer.Name)

不仅仅是Name,而是Customer_Name

$(document).ready(function () {
          $("#Customer_Name").autocomplete('@Url.Action("Name", "Reservation")', { minChars: 3   });//Never call... When I put a simple alert, it works !
});

这里似乎有些混乱,你正在使用的教程使用jQuery自动完成,但你似乎正在使用jQuery UI自动完成。两者略有不同,使用默认选项:

jQuery-UI自动完成

http://jqueryui.com/demos/autocomplete/):

<script type="text/javascript">
    $(document).ready(function () {
        $("#Customer_Name").autocomplete({ source: '@Url.Action("Name", "Reservation")', minLength: 3 });
    });
</script>

public ActionResult Name(string term)
{
    var customers = ...get a list of customer names filtered by term
    return Json(customers, JsonRequestBehavior.AllowGet);
}

jQuery自动完成

https://github.com/dyve/jquery-autocomplete

<script type="text/javascript">
    $(document).ready(function () {
        $("#Customer_Name").autocomplete('@Url.Action("Name", "Reservation")', { minChars: 3 });
    });
</script>

public ActionResult Name(string q)
{
    var customers = ...get a list of customer names filtered by q
    return Content(string.Join("\n", customers));
}