使用MVC 4 / Razor自动完成

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

到目前为止我尝试过的…

_布局

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

 
@Html.LabelFor(Function(model) model.Number)
@Html.EditorFor(Function(model) model.Number) @Html.ValidationMessageFor(Function(model) model.Number)
$(function () { $("#Number").autocomplete({ source: 'Home/Numbers', minLength: 1 }); });

当我运行我的应用程序并输入文本框时,没有任何反应。 我在“Numbers”函数中放了一个断点,它似乎永远不会被调用。

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

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

 @section scripts  End Section 

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

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

我建议你控制Chrome中的错误,以确保jQuery库正常工作。 如果没有问题,请尝试以下脚本:

 $(document).ready(function () { $("#Number").each(function () { $(this).autocomplete({ source: $(this).attr("data-autocomplete") }); }); }); 

然后在你的剃刀(C#)中:

  

如果要使用Razor Html Helpers而不是使用’input’标记,则id属性与Model.Member的名称相同。 请注意,在Controller中,您必须输入带有’term’名称的字符串,如代码中所写。 出于安全原因,您必须避免在显示站点技术的js文件中使用参数。 上面声明的方法从不使用js文件来获取资源的地址。

对于Viewpage

      

对于控制器:

 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 auto = new List(); 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 } ); } }