使用MVC 4 / Razor自动完成

时间:2012-11-19 14:16:15

标签: jquery asp.net-mvc razor

我想在尝试在MVC 4中添加自动完成功能时,我遗漏了一些明显的东西。从我在其他帖子中找到的内容中,我已经能够组合一个示例,但是我的控制器中的方法没有被调用。

到目前为止我的尝试......

_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

查看(我现在已经硬编码了Home / Numbers)

<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”函数中放了一个断点,它似乎永远不会被调用。

我的项目可以在http://www.filedropper.com/testapp

找到

3 个答案:

答案 0 :(得分:15)

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

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

因为你的脚本依赖于jQuery所以应该首先加载jQuery。

或者只是将@Scripts.Render声明移到布局中的head,然后您就不需要将代码放入scripts部分了(但最好使用部分)

答案 1 :(得分:1)

答案 2 :(得分:0)

对于Viewpage

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>

<input type="text" id="txtmasterserach" name="txtmasterserach" placeholder="City, region, district or specific hotel"  autocomplete="off"/> 
 <input type="hidden" name="hidenkeyvalues" id="MovieID" /> 

<script type="text/javascript">
    $(document).ready(function () {
        $("#txtmasterserach").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/Company/getautobox",
                    type: "POST",
                    dataType: "json",
                    data: { Prefix: request.term },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { value: item.Id, label: item.name };
                        }))
                    }
                })
            },
            select: function (event, ui) {
                $("#MovieID").val(ui.item.value);
                $("#txtmasterserach").val(ui.item.label);
                event.preventDefault();
                return false;
            },
            focus: function (event, ui) {
                $("#MovieID").val(ui.item.value);
               // $("#txtmasterserach").val(ui.item.label);
                event.preventDefault();
                return false;
            },
            messages: {
                noResults: "", results: ""
            }
        });
    });
    </script>

对于控制器:

public class companyController : Controller
{
public JsonResult getautobox(String Prefix)
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
        SqlCommand cmd = new SqlCommand("procedurename", con);
        cmd.Parameters.AddWithValue("@prefix", Prefix);
        cmd.CommandType = CommandType.StoredProcedure;
        DataSet ds = new DataSet();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(ds);
        List<autosearchdatalist> auto = new List<autosearchdatalist>();
        if (ds.Tables[0].Rows.Count > 0)
        {
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                auto.Add(new autosearchdatalist
                {
                    Id = ds.Tables[0].Rows[i]["Id"].ToString(),
                    name = ds.Tables[0].Rows[i]["hotelname"].ToString()
                });
            }
        }
        if (ds.Tables[1].Rows.Count > 0)
        {
            for (int i = 0; i < ds.Tables[1].Rows.Count; i++)
            {
                auto.Add(new autosearchdatalist { 
                    Id = ds.Tables[1].Rows[i]["Id"].ToString(),
                    name = ds.Tables[1].Rows[i]["hotelname"].ToString() 
                });
            }
        }
        if (ds.Tables[2].Rows.Count > 0)
        {
            for (int i = 0; i < ds.Tables[2].Rows.Count; i++)
            {
                auto.Add(new autosearchdatalist
                {
                    Id = ds.Tables[2].Rows[i]["Id"].ToString(),
                    name = ds.Tables[2].Rows[i]["hotelname"].ToString()
                });
            }
        }
        String msg = "";
        return Json(auto);
    }
}

保持路由器设置默认,否则操作不会调用

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "company", action = "Index", id = UrlParameter.Optional }
        );
    }
}