简体   繁体   English

使用MVC 4进行Jquery UI自动完成

[英]Jquery UI Autocomplete with MVC 4

I am using the jquery ui autocomplete in MVC 4 with Razor HTML. 我在使用Razor HTML的MVC 4中使用jquery ui autocomplete。 I am able to use it ok with hard coded values but I was wondering how I can connect it to the database so the the values coming up don't have to be hard coded. 我可以使用硬编码值,但我想知道如何将它连接到数据库,所以出现的值不必硬编码。

If you are using MVC4, then you should have an action created that you can access from the view (render the action url). 如果您正在使用MVC4,那么您应该创建一个可以从视图访问的操作(呈现操作URL)。 Then, you need to set this (url) as the source when setting up the autocomplete jquery. 然后,您需要在设置自动完成jquery时将此(url)设置为源。

The documentation for a remote source is here . 远程源的文档在这里

For MVC, it would look something like this: 对于MVC,它看起来像这样:

$( "#birds" ).autocomplete({
      source: "/MyController/OptionsAction",
      minLength: 2,
      select: function( event, ui ) {
        log( ui.item ?
          "Selected: " + ui.item.value + " aka " + ui.item.id :
          "Nothing selected, input was " + this.value );
      }
    });

Its better to use MVC's @URL.Action to ensure the URL is encoded correctly even if your view is one or ten folders deep. 最好使用MVC的@ URL.Action来确保URL被正确编码,即使您的视图是一个或十个文件夹深。

In the above example "/MyController/OptionsAction", would not work if you moved your view one folder down where as @URL.Action would continue to work. 在上面的示例“/ MyController / OptionsAction”中,如果您将视图移动到一个文件夹,那么@ URL.Action将继续工作。

Note the format of the ajax call is like this: 注意ajax调用的格式如下:

  1. Sending data: 发送数据:

url (where you are posting to) url(你要发布到的地方)

data (the data you are posting) 数据(您发布的数据)

type (the type of request being made: POST or GET or PUT. Default if left blank is GET) type(正在进行的请求类型:POST或GET或PUT。如果留空,则为默认值)

contentType (content type to use when sending data to the server. Better not to change unless necessary) contentType(将数据发送到服务器时使用的内容类型。除非必要,否则最好不要更改)

  1. Receiving data: 接收数据:

dateType (the datatype you are expecting back: in this case json) dateType(您期望的数据类型:在本例中为json)

success (function called if the request succeeds) 成功(如果请求成功则调用函数)

        $('#Country').autocomplete({
        source: function (request, response) {
            $.ajax({
                url: '@Url.Action("GetCountries", "User")',
                data: "{ 'CountrySearch': '" + $('#Country').val() + "' }",
                dataType: "json",
                type: "POST",
                contentType: 'application/json',
                success: function (data) {
                    response($.map(data, function (item) {
                        return JSON.parse(item);
                    }))
                },
                error: function (jqXhr, textStatus, errorThrown) { alert("Error '" + jqXhr.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')"); },
            })
        },
        minLength: 1,
    });

Where countries returns data from a database call like this: 国家/地区从数据库调用返回数据的方式如下:

{ "Countries":"["Australia", "Austria", "Canada", "United States"]" } {“国家”:“[”澳大利亚“,”奥地利“,”加拿大“,”美国“]”}

    public JsonResult GetCountries(string CountrySearch)
    {
        string[] Countries = new AddressManager().GetCountries(CountrySearch);
        string serialisedList = new JavaScriptSerializer().Serialize(Countries);
        return new JsonResult { Data = new { Countries = serialisedList }, ContentEncoding = Encoding.UTF8, ContentType = "text/plain", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM