Some time ago, write a user department's management page, need to obtain the user data in the background to achieve the English-Chinese retrieval function.
Also, after selecting an option, you need to trigger an event to interact with the background, displaying the department where the user is located in the ListBox control on the right side of the page.
One, Dojo's filteringselect component realizes the phonetic retrieval function
There are a lot of related introductions, including the classic "Pirate language" on the rewrite Dojo Filteringselect components to implement phonetic search function introduction (address http://cosbor.web-144.com/?p=38, http:// cosbor.web-144.com/?p=52). Because the author's demo background and pinyin4j jar package are based on the Java platform, I spent a little time to implement it. NET platform, and successfully implemented the registration of Filteringselect selected events. The principle of implementation, please refer to the "Pirate Language" blog in the analysis, right here. NET platform for the implementation of ideas to do a brief description, and posted the source code for everyone to refer to (here to the author's ideas to express thanks!) ):
First, introduce the Dojo Toolkit, add a "test" folder under the Dojo directory, and create a new Filteringselect.js file, as shown below:
The role of the Filteringselect.js file is to rewrite the Filteringselect component, "Pirate language" posting given the code list, for convenience to be posted as follows:
Copy Code code as follows:
Define ([
"Dojo/_base/declare",//Declare,
"Dojo/dom-attr",//Domattr.get
"Dijit/form/filteringselect"
], function (declare, domattr, Filteringselect) {
Return declare ("Test. Filteringselect ", [Filteringselect], {
Displayvalueattr:null,//Add a custom attribute that specifies the property field for the final display in the Filteringselect textbox
Summary
Overrides Dijit.form._autocompletermixin's method of the same name, enabling Filteringselect to support Displayvalueattr specify TextBox final display content. Instead of the default display searchattr specified field contents
_announceoption:function (/*node*/Node) {
if (!node) {
Return
}
Pull the text value from the item attached to the DOM node
var newvalue;
if (node = = This.dropDown.nextButton | |
node = = This.dropDown.previousButton) {
NewValue = node.innerhtml;
This.item = undefined;
This.value = ';
}else{
var item = This.dropdown.items[node.getattribute ("item")];
var displayattr = this.displayvalueattr!=null?this.displayvalueattr:this.searchattr;// Here to determine if the custom attribute is configured displayvalueattr
NewValue = (This.store._oldapi/Remove GetValue () for 2.0 (old Dojo.data API)
This.store.getValue (item, DISPLAYATTR): Item[displayattr]). toString ();//replace this.searchattr with Displayattr
This.set (' item ', item, False, NewValue);
}
Get the text this user manually entered (cut off autocompleted text)
This.focusNode.value = this.focusNode.value.substring (0, this._lastinput.length);
Set up ARIA activedescendant
This.focusNode.setAttribute ("Aria-activedescendant", Domattr.get (node, "id"));
AutoComplete the rest of the option to announce change
This._autocompletetext (NewValue);
},
});
});
Then, create a new WebForm page, place a Filteringselect control, the data source value for the Page class inherited Userliststr field, the page foreground code is as follows:
Copy Code code as follows:
<%@ Page title= "" Language= "C #" autoeventwireup= "true" codefile= "OrgRelation.aspx.cs" inherits= "Orgrelation"%>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title></title>
<script src= "Scripts/jquery-1.4.1-vsdoc.js" type= "Text/javascript" ></script>
<link href= "Scripts/dojo/dijit/themes/claro/claro.css" rel= "stylesheet" type= "Text/css"/>
<link href= "Scripts/dojo/dojo/resources/dojo.css" rel= "stylesheet" type= "Text/css"/>
<script src= "Scripts/dojo/dojo/dojo.js" type= "Text/javascript" ></script>
<script type= "Text/javascript" >
Parameter settings
Require ([
' Test/filteringselect ',
' Dojo/store/memory ',
' dojo/domready! '
], function (Filteringselect, Memory) {
var jsonstr = ' <%=userListStr%> ';
var json = Jquery.parsejson (JSONSTR);
var obj = {data: ""};
obj[' data '] = JSON;
var selectstore = new Memory (obj);
Create Filteringselect
var testselect = new Filteringselect ({
ID: "Testselect",
Name: "Test",
Value: "",
Store:selectstore,
Searchattr: ' py ',//Specify the field in which the input text box is used for retrieving
Labelattr: ' name ',//Specify the fields displayed in the Drop-down menu
Displayvalueattr: ' name ',//Specifies the field that appears in the input box when the Drop-down menu is selected
Required:false,
Autocomplete:false
}, "Testselect");
});
Register lost Focus Event
Window.onload = function () {
function Selblur () {
var guid = Dijit.byid (' Testselect '). attr (' value ');
Alert (GUID);
Window.location.href = "orgrelation.aspx?userid=" + GUID;
return false;
}
var sel = Dojo.byid ("Testselect");
Dojo.connect (SEL, "onblur", Selblur);
};
</script>
<body>
<form id= "Form1" method= "POST" runat= "Server" >
<div align= "center" id= "title" >
<strong> Edit User Department relations </strong>
</div>
<div style= "text-align:center;width:100%;p adding-top:100px;font-size:15px;" > Select User: <input id= "Testselect"/>
</div>
</form>
</body>
Finally, the user data is fetched in the page load event, and after serialization, the Userliststr field is assigned to the protected type. Here reference to Microsoft to obtain pinyin of the class library ChnCharInfo.dll, the code list as follows:
Copy Code code as follows:
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using Microsoft.International.Converters.PinYinConverter;
Using System.Text;
Using System.Text.RegularExpressions;
Using System.Web.Script.Serialization;
public partial class OrgRelation:System.Web.UI.Page
{
Protected string userliststr = String. Empty;
protected void Page_Load (object sender, EventArgs e)
{
if (! IsPostBack)
{
Getusers ();
}
}
class corresponding to the foreground page JSON object format
public class UserInfo
{
public string name {get; set;}
public string ID {get; set;}
public string py {get; set;}
}
protected void Getusers ()
{
Get user information, and the phonetic code for each record
List<user> list =new BLL. User (). Getusers ();
list<userinfo> userinfolist = new list<userinfo> ();
foreach (User item in list)
{
UserInfo userinfo= new UserInfo ();
Userinfo.id = Item. UserId;
Userinfo.name = Item. User Name;
userinfo.py = Getpy (item. UserName);
Userinfolist. ADD (UserInfo);
}
JavaScriptSerializer Jsonserializer = new JavaScriptSerializer ();
Perform serialization and assign values
Userliststr = Jsonserializer.serialize (userinfolist);
}
Related methods of #region Pinyin retrieval
<summary>
Gets a set of phonetic strings for a kanji character and handles tones and null values
</summary>
<param name= "ch" > Kanji characters </param>
<returns></returns>
public static list<string> getpinyins (char ch)
{
list<string> list = new list<string> ();
Chinesechar cc = new Chinesechar (CH); Get an object that contains Chinese character information
foreach (String item in CC.) Pinyins)
{
if (item!= NULL)
{
String temp = Item. Substring (0, item. LENGTH-1);
if (!list. Contains (temp))
{
List. ADD (temp);
}
}
}
return list;
}
<summary>
Get the phonetic Alphabet of a phrase (multiple tones take the first one)
</summary>
<returns></returns>
public static string getpy (String str)
{
Regex reg = new Regex (@ "[\u4e00-\u9fa5]");
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < str. Length; i++)
{
string ch = str[i]. ToString ();
if (Reg. IsMatch (CH))
{
string s = Getpinyins (str[i]) [0];
Sb. Append (S[0]);
}
Else
{
Sb. Append (CH);
}
}
Return SB. ToString ();
}
#endregion
}
So the function of pinyin retrieval is complete. But there are two unsatisfactory places: 1. Using pinyin search, it is not easy to use Chinese search, 2. Online search for a long time, there is no selection of changes to the event introduction, the code is only registered a loss of focus events, and in the background interaction is not very convenient (perhaps I am not familiar with Dojo events, welcome to Dojo The API has a study of the heroes steering).
Second, jQueryUI AutoComplete plug-in to achieve phonetic search function
In fact, jQueryUI also provides a very useful plug-in--autocomplete, it with the ChnCharInfo.dll class library with the use, not only to achieve the same excellent search function, but also can be a good solution to these two problems. may wish to take a look at:
Related components and referenced class libraries to be used: jquery-ui, Chinese Pinyin Conversion Language Pack class Library chncharinfo. dll and Json object serialization class library Newtonsoft.Json.dll, as follows:
1.WebForm aspx page implementation:
First introduce jquery-1.8.2.js, Jquery-ui-1.9.0.custom.js, Jquery-ui-1.9.0.custom.css, and then write the following script in the page load completion event:
Copy Code code as follows:
<script type= "Text/javascript" >
$ (function () {
$ ("#selCompate"). AutoComplete ({
Source: "Getuser.ashx",
Minlength:1,
The following are selected events
Select:function (event, UI) {
temp = Ui.item;
$ ("#hidcontactid"). Val (temp.id);
$ ("#hidcontactname"). Val (Temp.label);
$ ("#form2"). attr ("Action", "./orgrelation.aspx?contactid=" + temp.id + "&contactname=" + Temp.label);
$ ("#form2"). Submit ();
}
});
$ ("#selCompate"). Val ($ ("#hidcontactname"). Val ())
});
</script>
Source: "Getuser.ashx" in line 4th, refers to the address of the asynchronous request sent after the character is typed, GETUSER.ASHX is responsible for providing the requested client with user information that satisfies the JSON format, and the 5th line of minlength: is to start sending an asynchronous request when entering a few characters, and the Select:function (event, UI) {} On line 7th is selected. Ui.item represents the selected item; The hidden field value of the 第8-9 row is for the page refresh to retrieve information about the selected item, to be 第10-11 back to the page, and to send a POST request to the orgrelation.aspx with the ID and label of the currently selected item, which is the implementation that will select the user's The divisional query is displayed in the ListBox control on the right side of the page, and its service-side implementation is irrelevant to the content of this discussion and the code is not posted.
The complete code list for the page is as follows:
Copy Code code as follows:
<%@ Page title= "" Language= "C #" autoeventwireup= "true" codefile= "OrgRelation.aspx.cs"
inherits= "Orgrelation"%>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title></title>
<script src= "Scripts/jquery-1.8.2.js" type= "Text/javascript" ></script>
<script src= "Scripts/jquery-ui-1.9.0.custom.js" type= "Text/javascript" ></script>
<link href= "Css/ui-lightness/jquery-ui-1.9.0.custom.css" rel= "stylesheet" type= "Text/css"/>
<script type= "Text/javascript" >
$ (function () {
$ ("#selCompate"). AutoComplete ({
Source: "Getuser.ashx",
Minlength:1,
The following are selected events
Select:function (event, UI) {
temp = Ui.item;
$ ("#hidUserId"). Val (temp.id);
$ ("#hidUserName"). Val (Temp.label);
$ ("#form2"). attr ("Action", "./orgrelation.aspx? Userid= "+ temp.id +" &username= "+ Temp.label);
$ ("#form2"). Submit ();
}
});
$ ("#selCompate"). Val ($ ("#hidUserName"). Val ())
});
</script>
<body>
<form id= "Form2" "method=" Post "action="./orgrelation.aspx "Name=" Sendform "></form>
<form id= "Form1" method= "POST" runat= "Server" >
<input type= "hidden" id= "Hiduserid" name= "Hiduserid" value= "<%=currentUserId%>"/>
<input type= "hidden" id= "Hidusername" name= "Hidusername" value= "<%=currentUserName%>"/>
<asp:scriptmanager id= "ScriptManager1" runat= "Server" >
</asp:ScriptManager>
<div id= "Outline" >
<div align= "center" id= "title" >
<strong> Edit User Department relations </strong>
</div>
<div id= "Main" >
<table align= "center" >
<tr>
<td>
<div>
<b> Select User:</b>
<asp:updatepanel id= "UpdatePanel2" runat= "Server" >
<ContentTemplate>
<input type= "text" id= "selcompate" style= "line-height:10px"; margin-top:0px;
margin-left:0px; height:23px; "
runat= "Server"/>
</ContentTemplate>
</asp:updatepanel><br/>
<b> Select Department:</b>
</div>
<br/>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<TD valign= "Top" width= "41%" >
<div id= "Left" >
<asp:updatepanel id= "UpdatePanel1" runat= "Server" >
<ContentTemplate>
<asp:treeview id= "Treevieworgdata" runat= "Server" font-names= "Microsoft Ya Black" height= "385px"
Font-size= "11pt" forecolor= "Black" backcolor= "AliceBlue" ontreenodecollapsed= "treevieworgdata_treenodecollapsed"
Ontreenodeexpanded= "treevieworgdata_treenodeexpanded" showcheckboxes= "All" >
</asp:TreeView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</td>
<TD align= "center" valign= "Middle" width= "18%" >
<p>
<asp:button id= "btnaddorg" runat= "Server" width= "85px" text= "Add Department >>" height= "22px"
Borderstyle= "Solid" bordercolor= "Darkgray" backcolor= "Ghostwhite" font-size= "9pt"
onclick= "Btnaddorg_click" ></asp:Button></p>
<p>
<asp:button id= "btnremoveorg" runat= "Server" width= "85px" text= "<< Removal Department" height= "22PX"
Borderstyle= "Solid" bordercolor= "Darkgray" backcolor= "Ghostwhite" font-size= "9pt"
onclick= "Btnremoveorg_click" ></asp:Button></p>
</td>
<TD valign= "Top" align= "center" width= "41%" >
<div id= "Right" >
<asp:listbox id= "lborg" runat= "Server" width= "300px" height= "350px" "rows=" backcolor= "AliceBlue"
Font-size= "11pt" selectionmode= "multiple" >
</asp:ListBox>
</div>
</td>
</tr>
</table>
</div>
<br/>
<div align= "center" id= "Bottom" >
<asp:button id= "Btnback" runat= "Server" text= "• return •" Backcolor= "#f8f8ff"/>
<asp:button id= "btnsave" runat= "Server" text= "• Save ·" Backcolor= "#f8f8ff"
onclick= "Btnsave_click"/>
</div>
</div>
</form>
</body>
preparation of user data in 2.global.asax
Since the user data here is not constantly changing, considering that the search is frequently required to request data to the server, so the user data into the application, so that the search directly from the application, not every time to the database query.
The assignment of the Application object is done in the Application_Start event of the global application Global.asax, as follows:
Copy Code code as follows:
void Application_Start (object sender, EventArgs e)
{
Application.Lock ();
application["User"] = Getusers ();
Application.UnLock ();
}
In the GetUser method of obtaining the user's information, the acquisition of pinyin code is completed at the same time, the codes are as follows:
Copy Code code as follows:
Protected list<string> getusers ()
{
list<model.user> list = new BLL. User (). Getusers ();
list<string> userlist = new list<string> ();
foreach (Model.user item in list)
{
UserList. ADD (item. Id+ "|" +item. Name+ "|" +getpy (item. Name). Replace ("", ""). ToLower ());
}
return userlist;
}
<summary>
Gets a set of phonetic strings for a kanji character and handles tones and null values
</summary>
<param name= "ch" > Kanji characters </param>
<returns></returns>
public static list<string> getpinyins (char ch)
{
list<string> list = new list<string> ();
Microsoft.International.Converters.PinYinConverter.ChineseChar cc = new Microsoft.International.Converters.PinYinConverter.ChineseChar (CH); Get an object that contains Chinese character information
foreach (String item in CC.) Pinyins)
{
if (item!= NULL)
{
String temp = Item. Substring (0, item. LENGTH-1);
if (!list. Contains (temp))
{
List. ADD (temp);
}
}
}
return list;
}
<summary>
Get the phonetic Alphabet of a phrase (multiple tones take the first one)
</summary>
<returns></returns>
public static string getpy (String str)
{
Regex reg = new Regex (@ "[\u4e00-\u9fa5]");
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < str. Length; i++)
{
string ch = str[i]. ToString ();
if (string. IsNullOrEmpty (CH))
{
}
else if (Reg. IsMatch (CH))
{
string s = Getpinyins (str[i]) [0];
Sb. Append (S[0]);
}
Else
{
Sb. Append (CH);
}
}
Return SB. ToString ();
}
As for application consistent with data in the database, you can provide a generic handler updateapplication.ashx responsible for updating application (code is essentially the same as in Global.asax), and when the database changes, The application["Contact" object can be updated by accessing the updateapplication.ashx.
Returns data that matches the search criteria in 3.getuser.ashx
The server-side code that responds to the search event in Getuser.ashx is listed below:
Copy Code code as follows:
<%@ WebHandler language= "C #" class= "GetUser"%>
Using System;
Using System.Web;
Using BLL;
Using System.Collections.Generic;
Using System.Text.RegularExpressions;
Using System.Web.Script.Serialization;
Using Microsoft.International.Converters.PinYinConverter;
public class Getuser:javascriptserializer,ihttphandler
{
public void ProcessRequest (HttpContext context)
{
int i = 0;
List<string> strlist = context. application["User"] as list<string>;
String inputstr = context. Request.QueryString.Get ("term"). ToLower ();
list<useritem> userlist = new list<useritem> ();
foreach (String str in strlist)
{
string[] Userarr = str. Split (' | ');
if (I < 10)
{
Regex reg = new Regex (@ "^" + inputstr);
if (Reg. IsMatch (userarr[2]) | | Reg. IsMatch (Userarr[1])
{
Useritem item = new Useritem ();
Item.id = userarr[0];
Item.label = userarr[1];
Item.value = userarr[2];
Userlist.add (item);
i++;
}
}
Else
{
Break
}
}
Context. Response.ContentType = "Application/json";
String output = Newtonsoft.Json.JsonConvert.SerializeObject (userlist);
Context. Response.Write (output);
}
public bool IsReusable
{
Get
{
return false;
}
}
}
public class Useritem
{
public string ID {get; set;}
public string Label {get; set;}
public string value {get; set;}
}
The 17th line is the retrieve string Inputstr entered in the text box, where a regular expression is used to obtain a record whose name begins with a inputstr (Chinese search) or a record (phonetic search) that begins with a inputstr of phonetic code. If you need a blur retrieval feature, you can modify the regular expression on line 25th to: Regex reg = new regex (INPUTSTR); If you need more fields of composite retrieval (such as user phone number, email address, etc.), also as long as application to the image assignment when the relevant field information, in 26 rows if the match can be added.
Where Useritem is the class that provides the JSON object for the page, and the label is the required field, and the value of that field is what is displayed in the search box. After the data set is met, the Newtonsoft.Json.JsonConvert SerializeObject method is used to serialize and return to the client.
To this, that is to achieve the beginning of this article texture effect.