使用MVC 4/Razor自动完成 [英] Autocomplete with MVC 4 / Razor

查看:63
本文介绍了使用MVC 4/Razor自动完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想尝试在MVC 4中添加自动完成功能时遗漏了一些明显的东西.根据我在其他文章中发现的内容,我可以整理一个示例,但是未调用控制器中的方法.

I think I am missing something obvious while attempting to add autocomplete functionality in MVC 4. From what I have found in other posts I have been able to put together an example however the method in my controller is not being called.

到目前为止我一直在尝试...

What I have tried so far...

_Layout

@Styles.Render("~/Content/themes/base/css")
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryui")
@Scripts.Render("~/bundles/jqueryval")

控制器

Public Function Numbers(term As String) As ActionResult
    Return Json(New String() {"one", "two", "three", "four", "five", "six"}, JsonRequestBehavior.AllowGet)
End Function

查看(我现在已经硬编码了家庭/电话号码)

View (I have hard coded the Home/Numbers for now)

<div class="editor-label">
    @Html.LabelFor(Function(model) model.Number)
</div>
<div class="editor-field">
    @Html.EditorFor(Function(model) model.Number)
    @Html.ValidationMessageFor(Function(model) model.Number)
</div>

<script type="text/javascript">
    $(function () {
        $("#Number").autocomplete({
            source: 'Home/Numbers',
            minLength: 1
        });
    });
</script>

当我运行我的应用并在文本框中键入内容时,什么也没有发生.我在"Numbers"函数中设置了一个断点,似乎从未调用过它.

When I run my app and type in the textbox nothing happens. I have put a breakpoint in the "Numbers" function and it seems that it is never called.

可以在此处找到我的项目 http://www.filedropper.com/testapp

My project can be found here http://www.filedropper.com/testapp

推荐答案

如果在布局中body元素的底部和@RenderBody()之后有@Scripts.Render行,则需要将脚本放入scripts部分:

If you have the @Scripts.Render lines at the bottom of the body element in the layout and after the @RenderBody() you need to put your script in the scripts section:

@section scripts
<script type="text/javascript">
    $(function () {
        $("#Number").autocomplete({
            source: '@Url.Action("Numbers","Home")',
            minLength: 1
        });
    });
</script>
End Section

因为您的脚本依赖jQuery,所以应该先加载jQuery.

Because your script depends on jQuery so jQuery should be loaded first.

或者只是将@Scripts.Render声明移到布局中的head中,则无需将代码放入scripts部分(但最好使用该部分)

Or just move your @Scripts.Render declaration into the head in the layout then you don't need to put your code into the scripts section (but you are better off with using the section)

这篇关于使用MVC 4/Razor自动完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆