stay AspNet Mvc Use JQuery AutoComplete Components

Official documents :

http://api.jqueryui.com/autocomplete/#entry-examples

To use JQuery AutoComplete Components , Need to quote :

【1】.jquery.js

【2】.jquery-ui.js

【3】.jquery.ui.autocomplete.css

Then use it like this :

 var submitAutoCompleted = function(event, ui) {
var $input = $(this);
$input.val(ui.item.label); .......
}; var createAutoCompleted = function() {
var $input = $(this);
var ajaxOption = {
source: $input.attr("data-oft-ajax-autocompleted"), // tell AutoComplete Where components go to get data
select:submitAutoCompleted // After selecting an option , The logic to deal with
}; $input.autocomplete(ajaxOption);
} $("input[data-oft-ajax-autocompleted]").each(createAutoCompleted);

1.1 The goal is

For the text box to achieve automatic input prompt function . such as :

Enter in the text box “K”, Automatically prompt you for all the information you may want to enter with “K” The first option .

1.2 Implementation steps

First step : Create... In the controller AutoCompleted Of Aciton

Return type JsonResult. by JQuery AutoComplete Component supply Json Formatted data

 /// <summary>
///
/// </summary>
/// <param name="term"></param>
/// <returns>
//http://localhost:3951/Reviews/autocompleted?term= The old
// return JSON, The following format :
// [
// {"label":" Time honored restaurants 1000"},{"label":" Time honored restaurants 1001"},{"label":" Time honored restaurants 1002"},
// {"label":" Time honored restaurants 1003"},{"label":" Time honored restaurants 1004"},{"label":" Time honored restaurants 1005"},
// {"label":" Time honored restaurants 1006"},{"label":" Time honored restaurants 1007"},{"label":" Time honored restaurants 1008"},{"label":" Time honored restaurants 1009"}
// ]
/// </returns>
public ActionResult AutoCompleted(string term)
{
var model = _restaurantReviews.Where(r=>r.Name.ToLower().Contains(term.ToLower().Trim()))
.Take()
.Select(r=> new
{
label = r.Name // The field name of an anonymous object must be label, because ui.item.label
}); //serialize model into JSON format
return Json(model,JsonRequestBehavior.AllowGet);
}

It is worth noting that :

The field name of an anonymous object must be label, Because in the back js Method :

 var submitAutoCompleted = function(event, ui) {
var $input = $(this);
$input.val(ui.item.label); var $form = $input.parents("form:first");
$form.submit();
};

ui.item.label The name is fixed , See the fourth step of this article .

The second step : Add properties to the text box data-otf-autocompleted, For anchors

<input type="search" name="searchKey" 
data-oft-ajax-autocompleted="@Url.Action("AutoCompleted")" />
@Url.Action("AutoCompleted") It points to the definition of the first step Action:
 public ActionResult AutoCompleted(string term)

The third step : add to javascript Code processing

$(function () {
var createAutoCompleted = function() {
var $input = $(this);
var ajaxOption = {
source: $input.attr("data-oft-ajax-autocompleted") // tell AutoComplete Where components go to get data
}; $input.autocomplete(ajaxOption);
} $("input[data-oft-ajax-autocompleted]").each(createAutoCompleted);
});

To this step , The automatic prompt input function is realized .

 Be careful , When you don't see the effect , Try to check for the following reasons :
If the top js The code is already in existence js file ( such as :abc.js) Add , If the browser has loaded the js file , It may not be loaded again js file ,
This leads to the js There is no... In the file that we added in the third step js Code . The solution is : Refresh the page ( Press F5 key ).

Step four : Add when you select an item at the prompt , Logic to deal with :

stay ajaxOptin Add select Parameters :

What I want to demonstrate here is , When an item in the text box is selected , Leading to his father html Of Form Submit Form ,html The code is as follows :

<form method="post"
action="@Url.Action("Index")"
data-otf-ajax="true"
data-otf-ajax-updatetarget="#restaurantList">
<input type="search" name="searchKey" data-oft-ajax-autocompleted="@Url.Action("AutoCompleted")" />
</form>

then , stay js Add... To the file javascrtpt Code , bring

When an item in the text box is selected , Leading to his father html Of Form Submit Form

$(function () {
var submitAutoCompleted = function(event, ui) {
var $input = $(this);
$input.val(ui.item.label); var $form = $input.parents("form:first");
$form.submit();
}; var createAutoCompleted = function() {
var $input = $(this);
var ajaxOption = {
source: $input.attr("data-oft-ajax-autocompleted"), // tell AutoComplete Where components go to get data
select:submitAutoCompleted // After selecting an option , The logic to deal with
}; $input.autocomplete(ajaxOption);
} $("input[data-oft-ajax-autocompleted]").each(createAutoCompleted);
});

use FireFox Browser's Firebug plug-in unit , You can monitor :ui.item.label The name is fixed . obviously , When item.value When the value is not explicitly set , Automatically assigned to item.labe

item-- The explanation given on the official website :

  • item
    Type:  Object
     
    • label
      Type:  String
      The string to display for the item.
    • value
      Type:  String
      The value to insert into the input when the item is selected.

Other information :

http://www.cnblogs.com/yongheng178/archive/2011/11/15/2249632.html

【The end】

【ASP.Net MVC】 stay AspNet Mvc Use JQuery AutoComplete More articles on components

  1. 【ASP.Net MVC】AspNet Mvc Some summary

    AspNet Mvc Some summary RestaurantReview.cs using System; using System.Collections.Generic; using System.Comp ...

  2. MVC note 3:JQuery AutoComplete Components

    1. Introduce the following js and css <link href="@Url.Content("~/Content/Site.css")" rel="styles ...

  3. Bootstrap Typeahead/Jquery autocomplete Automatic completion

    Use Bootstrap Typeahead Components : Bootstrap Medium Typeahead A component is what is usually called automatic completion AutoComplete, Auto fill . The effect is shown in the figure : Realization way : 1. introduce ...

  4. 【 Set pieces 】ASP.NET MVC Quick start is free jQuery Control library (MVC5+EF6)

    Catalog [ Chapter one ]ASP.NET MVC Quick start of database operation (MVC5+EF6) [ Second articles ]ASP.NET MVC Quick start data annotation (MVC5+EF6) [ Third articles ]ASP.NET MVC Quick start security strategy ...

  5. ASP.NET MVC Client authentication for :jQuery Validation of the

    What we've been talking about before Model Verification is limited to server side verification , That is to say Web The server verifies the request data according to the corresponding rules . If we can do it on the client side ( browser ) Verify the data entered by the user first , This reduces the frequency of requests to the server , So as to alleviate W ...

  6. About html、asp、php template engine 、aspnet mvc、REST A little thought of

    Let's see if I'm right REST A little understanding of , Here is <rest actual combat > The preface to this book :      When I first started working on solving computational problems , Many people in the industry have a wish : Design the system as components that can be freely combined . Internet (I ...

  7. be based on asp.net(C#)MVC+ front end bootstrap+ztree+lodash+jquery technology -Angel Studio general rights management

    One .Angel Brief introduction of the simple general authority system of the studio AngelRM(Asp.net MVC Web api) Is based on asp.net(C#)MVC+ front end bootstrap+ztree+lodash+jquery technology ...

  8. AspNet MVC And T4, My customized view template

    One . Problems encountered At the beginning of the article, I want to talk about my confusion , In use AspNet MVC when , complete Action Compiling , Then add a view , At this time, an option window for adding views will pop up , as follows : Very familiar with it. , Go on with the above , I'll add a ...

  9. VS2015 All of a sudden, an error was reported ————Encountered an unexpected error when attempting to resolve tag helper directive &#39;@addTagHelper&#39; with value &#39;Microsoft.AspNet.Mvc.Razor.TagHelpers.UrlResolutionTagHelper

    Encountered an unexpected error when attempting to resolve tag helper directive '@addTagHelper' with ...

Random recommendation

  1. soj4271 Love Me, Love My Permutation (DFS)

    4271: Love Me, Love My Permutation Description Given a permutation of n: a[0], a[1] ... a[n-1], ( it ...

  2. newest DEDECMS SQL Inject 0day

    4 month 29 Daily news : Domestic security research team “ Know Chuangyu ” Said it had intercepted the latest DEDECMS SQL Inject 0day,DEDECMS The latest version is available on the official website 5.7 Also affected , By the time this alert was issued, no patch or solution has been provided , This vulnerability exploits ...

  3. jquery Mobile Click to display the loading waiting effect

    When you click a button or link , Trigger wait to load effect : <script> <!-- $(document).bind("mobileinit", function(){ }); ...

  4. ASP.NET(C#) GridView ( edit 、 Delete 、 to update 、 Cancel )

    from :http://my.oschina.net/dldlhrmc/blog/93458 The front desk code view source   print? 01 <%@ Page Language=" ...

  5. TCP&amp;UDP

    TCP( Transmission control protocol ) Establishing a connection , To form a channel for data transmission Big data transfer in connection ( Unlimited data size ) Connect through three handshakes , It's a reliable agreement , Safe delivery ( Three handshakes send a request to the server , Response request reply , send data ) It must be built ...

  6. [ translate ] .NET Core 2.1 Preview 1 Release

    [ translate ] .NET Core 2.1 Preview 1 Release original text : Announcing .NET Core 2.1 Preview 1 today , We announce the release of .NET Core 2.1 Previ ...

  7. Go In language Package problem

    Question 1 .Go Use Package What are the benefits of organizing source code ? 1. Any source code belongs to a package 2. Package organization makes code easy to read and reuse Question two .Go In language Package The type of Go There are two kinds of packages in the language . One is a package of executable programs . A kind of ...

  8. Single molecule fluorescence in situ hybridization (smFISH)

    single-molecule RNA fluorescence in situ hybridization (RNA smFISH) Single molecule fluorescence in situ hybridization (smFISH) It's a new method of gene expression analysis , can ...

  9. Mysql How to set auto increment fields

    #int : Field type alter table Table name modify Field name int auto_increment primary key

  10. Java The initial value of the variable

    Java If the variables in are not assigned values , Member variables are initialized by default , Local variables don't . For member variables int a;         // a The initial value of 0 The member variable in the following example a,b,c,d public class Va ...