使用JQuery&自动完成数据库-ASP.NET MVC [英] AutoComplete using JQuery & Database - ASP.NET MVC

查看:96
本文介绍了使用JQuery&自动完成数据库-ASP.NET MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很抱歉,这是重复的,但是即使在查看了有关该主题的其他几个问题之后,我仍然无法使我的工作正常.

I apologize this is sort of a repeat, however even after looking at several other questions on the topic, I'm still not able to get mine working.

我想在表单中使用JQuery AutoComplete小部件从数据库中的30K多个记录中进行选择.我认为我的问题出在.autocomplete函数的source上.

I want to use a JQuery AutoComplete widget in my form to select from 30K+ records in a database. I believe my issues stems around the source of the .autocomplete function.

HTML + JS

HTML + JS

@using (Html.BeginForm())
{
    @Html.LabelFor(model => model.Name)
    @Html.TextBoxFor(model =>model.Name, new { id="Search"})
}
<script type="text/javascript">
    $('#Search').autocomplete({
        source: '@Url.Action("GetVendors", "TestAutoComplete")',
        minLength: 3
    });
</script>

控制器动作

[HttpGet]
public JsonResult GetVendors(string Search)
{
  return Json(DB.VendorLookUp(Search), JsonRequestBehavior.AllowGet);
}

我知道我的DB.VendorLookUp方法有效(我已经对其进行了单独测试),并且GetVendors方法内部有一个断点,不会被击中.

I know my DB.VendorLookUp method works (I've tested it separately) and I have a breakpoint inside the GetVendors method which doesn't get hit.

在控制台中,我收到此错误:

In the console I get this error:

GET http://localhost:50848/TestAutoComplete/GetVendors?term=mic 500 (Internal Server Error)

(其中"mic"是我尝试的搜索). 我认为至少部分问题是当JS尝试获取"term"时,我的控制器方法除了字符串"Search"之外.

(where 'mic' is the search I attempted). I assume at least part of the problem is that my controller method is excepting string "Search", when the JS is trying to GET "term".

在此先感谢您的帮助.

我已经尝试过的事情:

Things I've already tried:

  • 在控制器操作中将参数搜索"更改为项"
  • 我的控制器操作中没有任何参数
  • 更新@ Url.Action()以将值传递给:
    • source: '@Url.Action("GetVendors", "TestAutoComplete", new {Search= $('#VendorSearch').val() })'
    • 但收到错误
    • Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.
    • Changing parameter "Search" to "term" in my controller action
    • Not having any parameters in my controller action
    • Updating the @Url.Action() to pass along the value to:
      • source: '@Url.Action("GetVendors", "TestAutoComplete", new {Search= $('#VendorSearch').val() })'
      • but get the error
      • Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

      更新:错误消息

      更新:

      感谢评论建议,通过网络查看错误->检查响应给了我一个有意义的错误.无论如何,我一直试图捕获js调用,所以我有2个控制器动作-一个带参数,一个不带参数.这使代码混乱.我删除了没有参数的操作,现在控制器操作行为正常,并且DB.VendorLookUp返回Vendor_VMs列表(控制器正确地将其转换为JSON对象).

      Thanks to comment suggestion, looking at the error via Network -> Inspect Response gave me a meaningful error. I was trying to catch the js call anyway I could so had 2 controller actions - one with a parameter, and one with no parameters. This was confusing the code. I removed the action with no parameters and now the controller action is behaving properly and DB.VendorLookUp is returning a List of Vendor_VMs (which the controller properly converts to a JSON object).

      但是,结果未正确返回-请参见下面的图像3.这些选项不在下拉列表中,并且不显示任何值.

      However, the results are not returning correctly - see image 3 below. The options are not in a dropdown and are not displaying any values.

      1. 如何更新cshtml/js以将名称传递给输入表单?
      2. 如何使值以适当的下拉方式显示?

      推荐答案

      这有效:1)在控制器中创建一个动作,并将RouteConfig设置为开始该动作

      This works: 1) Create an action in your controller and set the RouteConfig to start this action

      public class HomeController : Controller
      {
          public ActionResult Index20()
          {
              MyViewModel m = new MyViewModel();
              return View(m);
          }
      

      创建没有任何类型母版页的视图

      Create a view without any type of master page

      添加此视图模型:

      public class MyViewModel
      {
          public string SourceCaseNumber { get; set; }
      }
      

      转到管理Nuget程序包"或"PM控制台"并添加到MVC 5项目-Tim Wilson编写的用于MVC 5模型的Typeahead.js

      Go to Manage Nuget Packages or PM Console and add to MVC 5 project - Typeahead.js for MVC 5 Models by Tim Wilson

      将添加的HtmlHelpers.cs的命名空间更改为System.Web.Mvc.Html并重建

      Change the namespace for the added HtmlHelpers.cs to System.Web.Mvc.Html and rebuild

      添加此类:

      public class CasesNorm
      {
          public string SCN { get; set; }
      }
      

      将以下方法添加到您的控制器中:

      Add these methods to your controller:

      private List<Autocomplete> _AutocompleteSourceCaseNumber(string query)
          {
              List<Autocomplete> sourceCaseNumbers = new List<Autocomplete>();
              try
              {
                  //You will goto your Database for CasesNorm, but if will doit shorthand here
      
                  //var results = db.CasesNorms.Where(p => p.SourceCaseNumber.Contains(query)).
                  //    GroupBy(item => new { SCN = item.SourceCaseNumber }).
                  //    Select(group => new { SCN = group.Key.SCN }).
                  //    OrderBy(item => item.SCN).
                  //    Take(10).ToList();   //take 10 is important
      
                  CasesNorm c1 = new CasesNorm { SCN = "11111111"};
                  CasesNorm c2 = new CasesNorm { SCN = "22222222"};
                  IList<CasesNorm> aList = new List<CasesNorm>();
                  aList.Add(c1);
                  aList.Add(c2);
                  var results = aList;
      
                  foreach (var r in results)
                  {
                      // create objects
                      Autocomplete sourceCaseNumber = new Autocomplete();
      
                      sourceCaseNumber.Name = string.Format("{0}", r.SCN);
                      sourceCaseNumber.Id = Int32.Parse(r.SCN);
                      sourceCaseNumbers.Add(sourceCaseNumber);
                  }
              }
              catch (EntityCommandExecutionException eceex)
              {
                  if (eceex.InnerException != null)
                  {
                      throw eceex.InnerException;
                  }
                  throw;
              }
              catch
              {
                  throw;
              }
              return sourceCaseNumbers;
          }
      
          public ActionResult AutocompleteSourceCaseNumber(string query)
          {
              return Json(_AutocompleteSourceCaseNumber(query), JsonRequestBehavior.AllowGet);
          }
      
           throw;
          }
          catch
          {
              throw;
          }
          return sourceCaseNumbers;
      }
      
      public ActionResult AutocompleteSourceCaseNumber(string query)
      {
          return Json(_AutocompleteSourceCaseNumber(query), JsonRequestBehavior.AllowGet);
      }
      

      信用转到 http://timdwilson.github.io/typeahead-mvc-model /

      这篇关于使用JQuery&amp;自动完成数据库-ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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