Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to customize controls using the AJAX Extender

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Editor to share with you how to use the AJAX extender custom controls, I hope you will learn something after reading this article, let's discuss it together!

The necessity of mask editing function

In HTML, the only way to accept input data is to use tags. In ASP.NET, you simply use the TextBox control to encapsulate the input tag. One problem with this control is that it does not limit what users can type in it. However, by using a small amount of JavaScript code, you can filter out unwanted text. This is what was introduced last month. This month I'll add mask editing, which allows characters to be filtered as they are typed and displayed in a region-specific format. Mask editing can be used for filtering, validation, automatic formatting, and localization. You can also apply this feature to many real data types, including date, currency, time, zip code, phone number, social security number, or VAT ID, etc. The MaskedEdit extender is a free component in the AJAX control toolkit, and once you attach it to the TextBox control, you can control the input behavior in many common situations.

MaskedEdit Extender

In the AJAX control toolkit, the MaskedEdit extender supports some of the data formats specified by the MaskEditType enumeration type: the 2008 awards ceremony for technical books and original creators

Public enum MaskedEditType {None,Date,Number,Time,DateTime}

You can use this expander to enter numbers, dates, times, and dates / times. The extender determines the output format based on a given culture setting. The following code snippet shows a typical way to use the MaskedEdit extender for a text box that accepts date input:

< asp:TextBox runat= "server" ID= "TextBox1" / > < act:MaskedEditExtender ID= "MaskedEditExtender1" runat= "server" TargetControlID= "TextBox1" Mask= "999999" MaskType= "Date" / >

Listed in figure A. The input mask is defined mainly by two attributes: Mask and MaskType. The default value of Mask is "", which specifies the mask of characters acceptable to the extender. The default value of MaskType is "" and is used to indicate the mask type using any value defined by the MaskedEditType enumeration.

FigureAMaskedEdit Extender Properties

Attribute

Default value

Description

AcceptAMPM

False

A Boolean attribute that indicates whether AM/PM symbols should be used.

AcceptNegative

None

Indicates whether the negative sign (-) is allowed. The available values from the MaskedEditShowSymbol enumeration are: None, Left, and Right.

AutoComplete

True

A Boolean attribute indicating whether empty mask characters that are not specified by the user must be automatically filled in.

AutoCompleteValue

"

Indicates the default character to use when Autocomplete is enabled.

Century

1900

Indicates the century to be used when the date mask of the year has only two digits.

ClearMaskOnLostFocus

True

A Boolean attribute that indicates whether to delete the mask when the text box loses input focus.

ClearTextOnInvalid

False

A Boolean property that indicates whether to clear the text box when the user enters invalid text.

ClipboardEnabled

True

A Boolean property that indicates whether copy / paste using the clipboard is allowed.

ClipboardText

Your browser security settings don't permit the automatic execution of paste operations (the browser's security settings do not allow automatic pasting)

Indicates the prompt text to use when performing a clipboard paste operation.

CultureName

"

Gets and sets the name of the culture setting to use.

DisplayMoney

None

Indicates whether currency symbols are displayed. The available values from the MaskedEditShowSymbol enumeration are: None, Left, and Right.

ErrorTooltipCssClass

"

Gets and sets the CSS class for the tooltip message.

ErrorTooltipEnabled

False

A Boolean property indicating whether a tooltip message is displayed when the mouse hovers over a text box with invalid content.

Filtered

"

Gets and sets a list of valid characters for the mask type when the "C" placeholder is specified.

InputDirection

LeftToRight

Indicates the direction of text input. The available values from the MaskedEditInputDirection enumeration are: LeftToRight and RightToLeft.

Mask

"

Specifies the mask of characters that are acceptable to the extender.

MaskType

"

Use any value defined by the MaskedEditType enumeration to indicate the mask type.

MessageValidatorTip

True

A Boolean property that indicates whether a help message is displayed when the user types in the text box.

OnBlurCssNegative

"

Gets and sets the CSS class to use when the text box loses input focus and contains negative values.

OnFocusCssClass

"

Gets and sets the CSS class that is used when the text box gets the input focus.

OnFocusCssNegative

"

Gets and sets the CSS class to use when the text box gets the input focus and contains negative values.

OnInvalidCssClass

"

Gets and sets the CSS class to use when the text is invalid.

PromptCharacter

_

Gets and sets the prompt character to use for unspecified mask characters.

UserDateFormat

None

Indicates a specific date format. The available values are defined by the MaskedEditUserDateFormat enumeration.

UserTimeFormat

None

Indicates a specific time format. The available values are defined by the MaskedEditUserTimeFormat enumeration.

The MaskType property informs the extender that the target control will accept a specific data type. The Mask property (string type) indicates the sequence of characters that represent the valid input of the text box. For example, "12-6-07" and "12-09-2007" are valid dates, but they use different input masks.

To generate a mask, use a predefined symbol as a placeholder. Figure 1 lists the supported symbols. For example, the "999999.99" mask causes code to accept a number with a decimal point, with at most one thousand delimiter. Figure 2 shows the end user interface displayed in a text box expanded with the mask editor. The appearance of the currency symbol is controlled by the DisplayMoney property and prompts the user for each character that must be typed. The default prompt is an underscore, but you can change the prompt through the PromptCharacter property.

Figure1 input mask predefined placeholder

Symbol

Description

nine

Numeric character

L

Letter

$

Letters or spaces

C

Size-sensitive through custom write characters defined by the Filtered attribute

A

Letters or custom characters defined by the Filtered attribute

N

A number or custom character defined by the Filtered attribute

?

Arbitrary character

/

Date delimiter, depending on the current culture setting

:

Time delimiter, depending on the current culture setting

.

Decimal point, depending on the current culture setting

Thousand-bit delimiter, depending on the current culture setting

Escape character

{

Repeat the start of the mask

}

Repeating the Terminator of the mask

Figure 2 MaskedEdit extender in operation

For dates, you can also use other properties such as AcceptAMPM, Century, and even a custom user format other than the predefined format specified in the MaskedEditUserDateFormat enumeration, as follows:

Public enum MaskedEditUserDateFormat {None,DayMonthYear,DayYearMonth,MonthDayYear,MonthYearDay,YearDayMonth,YearMonthDay}

Many of the settings that affect the format applied by the MaskedEdit extender inherit from the current culture setting. The CultureName property indicates the culture settings to apply. Note that this setting overrides the culture setting defined for the page through the UICulture property in the @ Page directive.

Verify mask input

Although the mask extender provides dynamic formatting, there is another component, the mask validator, that ensures that any text entered is parsed to the expected type:

< act:MaskedEditValidator ID= "MaskedEditValidator1" runat= "server" ControlExtender= "MaskedEditExtender1" ControlToValidate= "TextBox2" IsValidEmpty= "False" Number is required "InvalidValueMessage=" Number is invalid "/ >

Figure B lists the properties exposed by the validator. The Text property of the masked text box returns formatted text. For a date, this property returns text similar to "02swap 04max 2007", and for a numeric input field, it returns text similar to "1200.00". Even if the currency symbol is displayed to the user on the page, the currency symbol is not included in the Text attribute.

FigureBMaskedEditValidator attribute

Attribute

Description

AcceptAMPM

Indicates whether the time value accepts AM/PM.

ConTRolToValidate

Indicates the ID of the text box to validate.

ConTRolExtender

Indicates the ID of the MaskedEditExtender control attached to the text box.

ClientValidationFunction

Gets and sets the name of the client-side JavaScript function used for custom validation.

EmptyValueBlurredText

Gets and sets the message that is displayed when the text box has no input focus and is empty.

EmptyValueMessage

Gets and sets the message that is displayed when the text box has input focus but is empty.

InitialValue

Gets and sets the initial value of the text box.

InvalidValueMessage

Gets and sets the message that is displayed when the text box has input focus but the content is invalid.

InvalidValueBlurredMessage

Gets and sets the message that is displayed when the text box has no input focus but the content is invalid.

IsValidEmpty

Indicates whether the text box can be left blank.

MaximumValue

Gets and sets the input * value.

MaximumValueBlurredMessage

Gets and sets the message to display when the * value is exceeded and the text box has no focus.

MaximumValueMessage

Gets and sets the message that is displayed when the * value is exceeded and the text box has focus.

MinimumValue

Gets and sets the minimum value entered.

MinimumValueBlurredText

Gets and sets the message to display when the minimum value is exceeded and the text box has no focus.

MinimumValueMessage

Gets and sets the message to display when the minimum value is exceeded and the text box has focus.

ValidationExpression

Gets and sets the regular expression used to validate the input.

TooltipMessage

Gets and sets the message that is displayed when the text box has input focus.

So how do you parse the value returned by Text into a logical data type (date or decimal)? You can use static Parse methods for DateTime and Decimal types. However, you must pay attention to the culture settings used. For example, "02amp 04amp 2007" can indicate either February 4 (US regional setting) or April 2 (European regional setting). In fact, there are no settings to ensure that the culture settings used by the input page match those used by the server page. There is a risk that the user types the date based on the European culture setting and treats it as a US culture date. To make matters worse, a value of 1200 entered in a numeric text box using Italian decimal and thousand delimiters may cause an exception to be thrown because parsers of type Decimal default to the US culture setting. Let's see how to adapt to solve these problems.

Keep in mind the fact that the extender uses the en-US culture setting by default unless the CultureName property is explicitly set. On the server, the system defaults to the value of the UICulture property on the Page class.

In your Codebehind class, first get the CultureInfo object that reflects the culture settings used by the user interface. You can continue as shown below:

String culture = "en-us"; if (! String.IsNullOrEmpty (MaskedEditExtender1.CultureName)) culture = MaskedEditExtender1.CultureName;CultureInfo info = new CultureInfo (culture)

Then call the Parse method to specify the format provider based on the selected culture setting:

NumberFormatInfo numberInfo = info.NumberFormat;DateTimeFormatInfo dateInfo = info.DateTimeFormat;DateTime when = DateTime.Parse (TextBox1.Text, dateInfo); decimal amount = Decimal.Parse (TextBox2.Text, numberInfo)

Figure 3 shows the behavior of the same page when typing with different culture settings.

Figure 3 parses data to .NET types using different culture settings

Automatic completion of text box

You must be very familiar with autocomplete. This feature predicts the words the user is typing based on the first few characters entered. Internet Explorer records all characters that have been typed in the address bar and form fields to complete the fill automatically.

Of course, this feature is entirely browser-based, and you can turn autocomplete and tagging on or off by setting the Autocomplete property to On or Off. The Autocomplete property is not a standard HTML property, but it is now supported by almost all browsers.

The AutoComplete extender in AJAX Control Toolbox provides the same behavior as the text box control, but it requires the developer to be responsible for all the logical rules that provide advice to the user. The extender creates a drop-down-style panel and places it in the lower-right corner of the text box. You can set the style and animation of the panel according to your preferences. The following code associates the Autocomplete extender with a text box:

< act:AutoCompleteExtender runat= "server" ID= "AutoComplete1" TargetControlID= "TextBox1" EnableCaching= "true" MinimumPrefixLength= "1" ServicePath= "Suggestions.asmx" ServiceMethod= "GetSuggestions" / >

The extender is bound to a Web service that provides list fill words. The MinimumPrefixLength property indicates when the control invokes the Web service. The typed text will be used as input to the specified Web service method. The response result is used to populate the drop-down list. Caching can also be enabled. In this way, you only need to invoke the Web service once when you type the same prefix multiple times. In addition, depending on how the Web service retrieves its data, you can enable caching on the server to reduce additional round trips to and from the database or other remote data stores.

Figure C lists all the attributes supported by the AutoComplete extender. It should be noted that in addition to the properties listed here, other extenders have additional properties. The TargetControlID property, which is used to get and set the ID;Enabled property of the extension control, allows you to programmatically turn on and off the extender's functionality, which is set to True by default. There is also the BehaviorID property, which is used to set the name of the client JavaScript object that provides the extended behavior. *, and there are two important attributes: ClientState and EnableClientState. The ClientState property is a string property that maintains the client state of the extender. This state is maintained with a hidden field, whose name can be set through the ClientStateFieldID property. The EnableClientState property is a Boolean property that controls whether client state is enabled.

FigureCAutoComplete Extender Properties

Attribute

Description

Animations

Sets the animation to play when the pop-up panel is shown or hidden.

CompletionInterval

Gets and sets the number of milliseconds after which the extender will use the bound Web service to get suggestions.

CompletionListCssClass

Indicates the CSS class that is used to style the pop-up panel of the completion list.

CompletionListHighlightedItemCssClass

Indicates the CSS class used to style highlighted items in the completion list pop-up panel.

CompletionListItemCssClass

Indicates the CSS class used to style items in the completion list pop-up panel.

CompletionSetCount

Gets and sets the number of suggestions obtained from the bound Web service. The default value is 10.

ContextKey

A string property that indicates any page or user-specific information to be passed to the bound Web service.

DelimiterCharacters

Indicates one or more characters that the extender will use to mark the contents of the text box. The Web service will then use a tag to provide advice. This property is not set by default.

EnableCaching

A Boolean property that indicates whether client caching is enabled. True by default.

FirstRowSelected

A Boolean attribute that indicates whether to automatically select * * options in the list. False by default.

MinimumPrefixLength

Gets and sets the minimum number of characters in the text box buffer that can trigger binding for the Web service. The default value is 3.

ServiceMethod

Gets and sets the name of the method used to invoke the bound Web service.

ServicePath

Gets and sets the URL of the bound Web service.

UseContextKey

A Boolean property that indicates whether the value of the ContextKey attribute should be used if it is specified. False by default.

Build an autocomplete Web service

The Web service used in conjunction with the AutoComplete extender is an ASP.NET AJAX scripting service. This service looks almost like a regular ASP.NET Web service, except that the class of the service must be decorated with the ScriptService attribute. If the Web service you are using is missing this attribute, each request to the relevant ASMX endpoint will result in an HTTP 500error. The exception interface is not displayed to the end user (the extender is always properly degraded), and a pop-up panel with suggestions is not displayed:

[ScriptService] public class SuggestionService: WebService {...}

Note that the script service does not need the WebService attribute, but it can still be used to provide namespace information.

The name of any public method on the script service class marked with the WebMethod attribute can be successfully assigned to the ServiceMethod attribute on the extender. The method used to provide advice must have the following signature:

WebMethod] public string [] GetSuggestions (string prefixText, int count)

The * parameters are the prefix text used to generate the proposal. It is the same as the current content of the text box, and its length is not less than the value of the MinimumPrefixLength property. The Count parameter indicates the number of recommendations to be provided. The value of the Count parameter comes from the value of the CompletionSetCount property.

If you plan to take advantage of a context keyword (a string property that indicates any page or user-specific information to be passed to the bound Web service), you should provide an override method for any Web service method to be used. Here is the signature:

Public string [] GetSuggestions (string prefixText, int count, string contextKey) {...}

The return value is always packaged as an array of strings. Due to the use of the ScriptService attribute, all communication between the server and the client will take place through the JavaScript Object Notation (JSON) string.

You can take advantage of any attribute supported on the Web service method to improve service performance. For example, the CacheDuration attribute on the WebMethod attribute can force the service to cache the response to a method call within a specified period. Similarly, you can enable session state if the logic of the method does require session state.

Figure 4 shows a sample service that provides recommendations for a customer name from the Northwind database. From a performance point of view, it may not sound like a good idea to type a few characters to invoke a Web service. However, there are some factors that make autocompletion more practical than you think. The client cache of the AutoComplete extender is based on local memory and is never maintained through hidden fields. The completion list associated with the prefix can be stored in an internal array by using the specified prefix as the keyword. The list is retrieved whenever the same prefix is shredded in the text box buffer. Therefore, if the user repeatedly types the same prefix, no new request will be made to the back-end service over the network.

Example of Figure4 recommended service

Using System;using System.Web;using System.Web.Services;using System.Web.Services.Protocols;using System.Data;using System.Data.SqlClient;using System.Web.Script.Services; [WebService (Namespace = "MsdnMag.Articles")] [ScriptService] public class SuggestionService: System.Web.Services.WebService {[WebMethod] public string [] GetSuggestions (string prefixText, int count) {DataView data = GetData (); data = FilterData (data, prefixText); int totalCount = data.Count;if (data.Count > count) totalCount = count String [] suggestions = new string [totalCount]; int I = 0 companyname foreach (DataRowView row in data) {suggestions [ionization +] = (string) row ["companyname"]; if (I > = count) break;} return suggestions;} private DataView GetData () {DataView view = (DataView) HttpContext.Current.Cache ["Suggestions"]; if (view = null) {SqlDataAdapter adapter = new SqlDataAdapter ("SELECT * FROM customers", "..."); DataTable table = new DataTable (); adapter.Fill (table); view = table.DefaultView HttpContext.Current.Cache ["Suggestions"] = view;} return view;} private DataView FilterData (DataView view, string prefix) {view.RowFilter = String.Format ("companyname LIKE'{0}%'", prefix); return view;}}

Client-side caching is obviously more efficient than server-side caching. Server-side caching can reduce some round trips to and from the database, but not to the Web server. In the code shown in figure 4, the service loads all customers in the database and stores the list in the ASP.NET cache. Then, retrieve the customer list from the cache and filter out the names that match the prefix.

As mentioned earlier, the Web service used to provide recommendations must be an ASP.NET AJAX scripting service and communicate with the client through JSON. You need to determine whether the service is also publicly accessible to SOAP clients. ASP.NET AJAX services have dual functions by default: JSON and SOAP. You can close the SOAP client by adding the following code to the host application's web.config file:

< system.web > < webServices > < protocols > < clear / > < / protocols > < / webServices > < / system.web >

Using ASP.NET 3.5, you can also bind an AutoComplete extender to a Windows ®Communication Foundation (WCF) service through a service (SVC) endpoint. The extender uses the following JavaScript code instead of calling:

Sys.Net.WebServiceProxy.invoke (this.get_servicePath (), this.get_serviceMethod (), false, params, Function.createDelegate (this, this._onMethodComplete), Function.createDelegate (this, this._onMethodFailed), text)

For the WebServiceProxy class in the Microsoft AJAX client library, the key is to specify that the endpoint can successfully process the request when the content type request title is set to "application/json; charset=utf-8". To create a WCF service to provide advice, you need a class similar to the following:

[ServiceContract (Namespace = "MsdnMag.Services")] [AspNetCompatibilityRequirements (RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class MySuggestionService {[OperationContract] public string [] GetSuggestions (string prefixText, int count) {.}}

In addition, a SVC endpoint is required, as follows:

<% @ ServiceHost Language= "C#" Service= "MySuggestionService" CodeBehind= "~ / App_Code/WcfSuggestions.cs"% >

To register a service, you can use the webHttpBinding binding model to add explicit endpoints to the serviceModel section of the web.config file. Alternatively, you can specify the Factory property of the @ ServiceHost directive and point it to the following classes:

System.ServiceModel.Activation.WebScriptServiceHostFactory

Style the AutoComplete extender

The AutoComplete extender supports styling properties that allow you to specify the CSS class to use for the styling portion of the control. In particular, you can style the entire pop-up area, including the border and background color. You can also use different settings for all items and selected items. No predefined styles are provided for options. By default, the * * elements in the drop-down list are not selected to complete. However, you can use the FirstRowSelected property to force the automatic selection of * * items.

The completion list is displayed after the specified number of milliseconds. The elapsed time is controlled by the CompletionInterval property, which is set to one second by default. After the specified time, the extender invokes the service to get a list of suggestions.

You can use the Animations property to add actions to the opening process of the list. You can define animation for two events: OnShow and OnHide. Animation is performed through the Animation extender and its associated framework (see the example in figure 5).

Figure5 uses the Animations attribute

< Animations > < OnShow > < Sequence > < OpacityAction Opacity= "0" / > < HideAction Visible= "true" / > < Parallel Duration= ".4" > < FadeIn / > < / Parallel > < / Sequence > < / OnShow > < OnHide > < Parallel Duration= ".4" > < FadeOut / > < / Parallel > < / OnHide > < / Animations >

The animation script adds fade in and fade out effects to the completion list. The OpacityAction node is used to set transparency, and the HideAction node is used to display the completion list and any other visual effects. *, FadeIn and FadeOut actions perform the dilution effect. Figure 6 shows a dynamic completion list.

Figure 6 AutoComplete extender in operation

Do a progressive search on the list

Have you ever tried to find a specific item in a long list, for example, the name of a country in a list that contains all the countries in the world? If you type some consecutive letters fast enough, you may find the country you want, but even if you hesitate for a few milliseconds, the next letter you type will become the letter of the search term. The ListSearch extender addresses this limitation. Note that this extender applies only to ASP.NET Web and HTML controls and cannot be used with regular HTML elements such as SELECT or OPTION.

Therefore, the main advantage of the ListSearch extender is that it allows you to search for items in a list control by typing letters and prevents the search string from being lost after a few seconds; instead, the search string remains in place until you press Esc or postback to the server, including all or part of the postback. Any other characters typed are appended to the search string to further narrow the search. The following describes how to use the ListSearch extender:

< act:ListSearchExtender ID= ListSearchExtender1 "runat=" server "TargetControlID=" DropDownList1 "PromptCssClass=" Prompt "/ >

The extender provides three main properties: PromptText, PromptCssClass, and PromptPosition. All of these properties are related to prompt text, which is a string displayed around the target control to provide visual feedback about the text being searched. The default value for PromptText is "Type to search". When the target list control gains focus, this text is usually displayed above the control. The PromptCssClass property gets and sets the name of the CSS class to apply to the prompt message. The prompt text is replaced by the search text typed by the user. The Esc and Del buttons play an important role here. The Esc button clears the current search and resets the list to the default selection. The Del button removes the last typed character from the search text and updates the selection in the list. In addition, the function of the Animations attribute is the same as discussed in the AutoComplete extender section above.

Pop-up context menu

It is good to give users the option of what they can do when they are about to perform an action. Tooltips were a huge improvement a few years ago because they provided pop-up additional information about specific control roles. The advent of dynamic HTML makes HTML tooltips possible.

Today, HoverMenu extenders can display pop-up panels next to any ASP.NET server control. One of the most common uses of this extender is to display a context menu activated by a mouse movement event rather than a right-click.

The HoverMenu extender is activated when the user moves the mouse over the control. Therefore, the specified pop-up panel is displayed near the control; the actual location can be controlled programmatically. In addition, you can apply a CSS style to a control to mark it in an eye-catching format.

The radio button menu shown in figure 7 provides advice on the text to insert in the text box. The following is the declaration of the relevant extender:

Figure 7 HoverMenu extender in operation

< act:HoverMenuExtender ID= HoverMenu1 "runat=" server "TargetControlID=" TextBox1 "PopupControlID=" Panel1 "/ >

The Panel1 control contains a list of radio buttons. To ensure that all selections are processed in the text box target control, you define a SelectedIndexChanged event in the radio button list and encapsulate all related actions in the UpdatePanel control. For more information, see the source code attached to the download for this column.

In addition to the PopupControlID and TargetControlID properties, the HoverMenu extender provides a number of other properties. The HoverCssClass property indicates the CSS class to apply to the target control when the hover menu is visible. The PopupPosition property indicates the pop-up position relative to the target control, and possible values include Top, Right, Left, and Bottom. The OffsetX and OffsetY properties are used to set horizontal and vertical offsets relative to the determined position. The PopDelay attribute indicates the delay between the DOM event and the display of the pop-up menu. The default is 100 milliseconds.

When you hover over the DOM event, the event triggers the HoverMenu extender. There is not much difference between HoverMenu extender and Popup extender. The main differences are activation mechanisms and triggers. The Popup extender is activated when the user points the focus to a specific target control. To activate the HoverMenu extender, the user simply moves the mouse over the appropriate control.

After reading this article, I believe you have some understanding of "how to use AJAX Extender Custom controls". If you want to know more about it, please follow the industry information channel. Thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report