Script control что это

Обновлено: 08.05.2024

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

Provides an abstract base class for a script control.

Комментарии

ScriptControlБазовый класс тестирует страницу для ScriptManager элемента управления на PreRender этапе производного элемента управления. ScriptControlБазовый класс также гарантирует, что производный элемент управления вызывает методы ScriptManager элемента управления для регистрации скрипта во время Render события. Это включает регистрацию ScriptDescriptor объектов для, ScriptControl когда Render вызывается метод. RenderМетод гарантирует, что ScriptDescriptor объекты не подготавливаются к просмотру, пока ScriptControl не будет отображен сам объект. Это позволяет ScriptControl работать внутри закрытого WebPart элемента управления.

В любой класс, производный от, можно добавить столько дескрипторов и типов, сколько необходимо ScriptControl .

Events

Occurs when the server control binds to a data source.

Occurs when the server control is initialized, which is the first step in its lifecycle.

Occurs when the server control is loaded into the Page object.

Occurs after the Control object is loaded but prior to rendering.

Occurs when the server control is unloaded from memory.

Properties

Gets or sets the access key that allows you to quickly navigate to the Web server control.

Gets the browser-specific adapter for the control.

Gets or sets the application-relative virtual directory of the Page or UserControl object that contains this control.

Gets the collection of arbitrary attributes (for rendering only) that do not correspond to properties on the control.

Gets or sets the background color of the Web server control.

Gets the control that contains this control's data binding.

Gets or sets the border color of the Web control.

Gets or sets the border style of the Web server control.

Gets or sets the border width of the Web server control.

Gets a value that indicates whether the server control's child controls have been created.

Gets or sets the algorithm that is used to generate the value of the ClientID property.

Gets a character value representing the separator character used in the ClientID property.

Gets a ControlCollection object that represents the child controls for a specified server control in the UI hierarchy.

Gets the style of the Web server control. This property is used primarily by control developers.

Gets a value indicating whether a Style object has been created for the ControlStyle property. This property is primarily used by control developers.

Gets or sets the Cascading Style Sheet (CSS) class rendered by the Web server control on the client.

Gets a reference to the naming container if the naming container implements IDataItemContainer.

Gets a reference to the naming container if the naming container implements IDataKeysControl.

Gets a value indicating whether a control is being used on a design surface.

Gets or sets a value indicating whether the Web server control is enabled.

Gets or sets a value indicating whether themes apply to this control.

Gets or sets a value indicating whether the server control persists its view state, and the view state of any child controls it contains, to the requesting client.

Gets a list of event handler delegates for the control. This property is read-only.

Gets the font properties associated with the Web server control.

Gets or sets the foreground color (typically the color of the text) of the Web server control.

Gets a value indicating whether the control has attributes set.

Gets a value indicating whether the current server control's child controls have any saved view-state settings.

Gets or sets the height of the Web server control.

Gets or sets the programmatic identifier assigned to the server control.

Gets the character used to separate control identifiers.

Gets a value indicating whether controls contained within this control have control state.

Gets a value indicating whether the control is enabled.

Gets a value that indicates whether the server control is saving changes to its view state.

Gets a value indicating whether view state is enabled for this control.

Gets a value indicating whether the control participates in loading its view state by ID instead of index.

Gets a reference to the server control's naming container, which creates a unique namespace for differentiating between server controls with the same ID property value.

Gets a reference to the Page instance that contains the server control.

Gets a reference to the server control's parent control in the page control hierarchy.

Gets information about the container that hosts the current control when rendered on a design surface.

Gets or sets the skin to apply to the control.

Gets a collection of text attributes that will be rendered as a style attribute on the outer tag of the Web server control.

Gets a value that indicates whether the control should set the disabled attribute of the rendered HTML element to "disabled" when the control's IsEnabled property is false .

Gets or sets the tab index of the Web server control.

Gets the HtmlTextWriterTag value that corresponds to this Web server control. This property is used primarily by control developers.

Gets the name of the control tag. This property is used primarily by control developers.

Gets or sets a reference to the template that contains this control.

Gets the virtual directory of the Page or UserControl that contains the current server control.

Gets or sets the text displayed when the mouse pointer hovers over the Web server control.

Gets the unique, hierarchically qualified identifier for the server control.

Gets or sets a value that indicates whether the control checks client input from the browser for potentially dangerous values.

Gets a dictionary of state information that allows you to save and restore the view state of a server control across multiple requests for the same page.

Gets a value that indicates whether the StateBag object is case-insensitive.

Gets or sets the view-state mode of this control.

Gets or sets a value that indicates whether a server control is rendered as UI on the page.

Gets or sets the width of the Web server control.

Script Control Класс

Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.

Предоставляет абстрактный базовый класс для элемента управления сценария.

Свойства

Возвращает или задает клавишу доступа, обеспечивающую быстрый переход к серверному веб-элементу управления.

Возвращает конкретный адаптер браузера для элемента управления.

Возвращает или задает относительно приложения виртуальный каталог объекта Page или UserControl, который содержит этот элемент управления.

Получает коллекцию произвольных атрибутов (только для отрисовки), которые не соответствуют свойствам элемента управления.

Получает или задает цвет фона серверного веб-элемента управления.

Возвращает элемент управления, который содержит привязку данных элемента управления.

Возвращает или задает цвет рамки элемента управления Веба.

Получает или задает стиль границы серверного веб-элемента управления.

Возвращает или задает ширину границы серверного веб-элемента управления.

Возвращает значение, которое указывает, созданы ли дочерние элементы управления серверного элемента управления.

Возвращает или задает алгоритм, используемый для создания значения свойства ClientID.

Возвращает значение символа разделителя, используемого в свойстве ClientID.

Возвращает объект ControlCollection, который представляет дочерние элементы управления для указанного элемента управления сервера в иерархии пользовательского интерфейса.

Возвращает или задает стиль серверного веб-элемента управления. Это свойство используется преимущественно разработчиками элементов управления.

Возвращает значение, определяющее, был ли объект Style создан для свойства ControlStyle. Этот свойство в основном используется разработчиками элементов управления.

Возвращает или задает класс каскадных листов стилей (CSS), преобразовываемый для просмотра в серверном веб-элементе управления на клиентском компьютере.

Возвращает ссылку на контейнер именования, если контейнер именования реализует класс IDataItemContainer.

Возвращает ссылку на контейнер именования, если контейнер именования реализует класс IDataKeysControl.

Возвращает значение, указывающее, используется ли элемент управления на поверхности разработки.

Возвращает или задает значение, определяющее, включен ли серверный веб-элемент управления.

Возвращает или задает значение, указывающее, применяются ли темы к этому элементу управления.

Получает или задает значение, указывающее запрашивающему клиенту, сохраняет ли серверный элемент управления состояние представления и состояние представления своих дочерних элементов управления.

Возвращает список делегатов обработчиков событий элемента управления. Это свойство доступно только для чтения.

Возвращает свойства шрифта, связанные с серверным веб-элементом управления.

Возвращает или задает основной цвет (обычно это цвет текста) для серверного веб-элемента управления.

Получает значение, определяющие наличие атрибутов у элемента управления.

Возвращает значение, которое указывает на наличие сохраненных параметров состояния представления у дочернего элемента серверного элемента управления.

Получает или задает высоту серверного веб-элемента управления.

Возвращает или задает программный идентификатор, назначенный серверному элементу управления.

Возвращает символ, используемый для разделения идентификаторов элементов управления.

Возвращает значение, указывающее, имеют ли элементы управления в этом элементе управления состояние элемента управления.

Возвращает значение, определяющее, включен ли элемент управления.

Возвращает значение, отражающее сохранение изменений в состояние представления серверного элемента управления.

Возвращает значение, указывающее, используется ли состояние представления для этого элемента управления.

Возвращает значение, указывающее, участвует ли элемент управления в загрузке состояния представления ID вместо индекса.

Возвращает ссылку на контейнер именования элемента управления, создающий уникальное пространство имен для различения серверных элементов управления с одинаковыми значениями свойства ID.

Возвращает ссылку на экземпляр Page, содержащий серверный элемент управления.

Возвращает ссылку на родительский элемент управления серверного элемента управления в иерархии элементов управления страницы.

Возвращает сведения о контейнере, который содержит текущий элемент управления при визуализации на поверхности конструктора.

Возвращает или задает обложку, применяемую к элементу управления.

Возвращает коллекцию атрибутов текста, которые будут отображены в виде атрибута стиля на внешнем теге серверного веб-элемента управления.

Получает значение, указывающее, должен ли элемент управления устанавливать для атрибута disabled отрисовываемого элемента HTML значение disabled, если для свойства элемента управления IsEnabled задано значение false .

Возвращает или задает индекс перехода по клавише Tab для серверного веб-элемента управления.

Возвращает значение HtmlTextWriterTag, которое соответствует этому элементу управления веб-сервера. Это свойство используется преимущественно разработчиками элементов управления.

Возвращает имя тега элемента управления. Это свойство используется преимущественно разработчиками элементов управления.

Возвращает или задает ссылку на шаблон, содержащий этот элемент управления.

Возвращает виртуальный каталог Page или UserControl, содержащий текущий серверный элемент управления.

Возвращает или задает текст, который отображается при наведении указателя мыши на серверный веб-элемент управления.

Возвращает уникальный идентификатор серверного элемента управления в иерархии.

Возвращает или задает значение, указывающее, проверяет ли элемент управления полученный из браузера клиентский ввод на предмет потенциально опасных значений.

Возвращает словарь сведений о состоянии, позволяющих сохранять и восстанавливать состояние представления серверного элемента управления при нескольких запросах одной и той же страницы.

Возвращает значение, указывающее, является ли объект StateBag нечувствительным к регистру.

Возвращает или задает режим состояния представления данного элемента управления.

Получает или задает значение, указывающее, отрисовывается ли серверный элемент управления как пользовательский интерфейс на странице.

Получает или задает ширину серверного веб-элемента управления.

Конструкторы

Инициализирует новый экземпляр класса ScriptControl в производном классе.

Explicit Interface Implementations

Gets an attribute of the Web control with the specified name.

Sets an attribute of the Web control to the specified name and value.

For a description of this member, see ControlBuilder.

For a description of this member, see GetDesignModeState().

For a description of this member, see SetDesignModeState(IDictionary).

For a description of this member, see SetOwnerControl(Control).

For a description of this member, see UserData.

For a description of this member, see DataBindings.

For a description of this member, see HasDataBindings.

For a description of this member, see Expressions.

For a description of this member, see HasExpressions.

For a description of this member, see AddParsedSubObject(Object).

When overridden in a derived class, registers the ScriptDescriptor objects for the control.

When overridden in a derived class, registers script files for the control.

Методы расширения

Возвращает источник данных, связанный с элементом управления данными, для заданного элемента управления.

Возвращает шаблон поля для заданного столбца в контейнере именования заданного элемента управления.

Возвращает объект метатаблицы для контейнерного элемента управления данными.

This article may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist. To maintain the flow of the article, we've left these URLs in the text, but disabled the links.

In the October 1999 issue of MSJ, you covered the workings of Microsoft® Active Scripting in detail. While I found the suggestions very useful for my project, it seemed to me that writing all that site code was a bit much. Isn't there already a prepackaged site that I can use somewhere?

A

Yes, it turns out that you don't have to write all the scripting plumbing code yourself. There's already an ActiveX® control available from Microsoft that has all the site plumbing wrapped up for you, aptly named the Microsoft ScriptControl. Before going over the ScriptControl, let's review the Active Scripting architecture.

Active Scripting Redux

There are two sides to the Active Scripting story: Active Scripting engines and Active Scripting hosts. An Active Scripting engine is a COM component that implements the scripting interfaces and understands how to parse the syntax of a certain scripting language. Microsoft provides scripting engines for VBScript and JScript®. Because the Active Scripting mechanism is hidden behind COM interfaces, you can include multiple disparate scripting engines in your application. In fact, you don't even need to use scripting engines from Microsoftâ€"you can use one from another vendor or write your own.
An Active Scripting engine is just like any other COM object: you create an instance of the object using CoCreateInstance and acquire interfaces through QueryInterface. Active Scripting engines usually implement the following interfaces: IActiveScript, IActiveScriptDebug, IActiveScriptParse, IActiveScriptStats, IObjectSafety, IRemoteApplicationDebugEvents, and IVariantChangeType.
There are two ways to get script code into the scripting engine. The first way is to ask the scripting engine to load the script text from some persistent medium (through one of the IPersistXXX interfaces). Alternatively, you can represent the scripting text as a BSTR and load it into the engine using IActiveScriptParse.
Active Scripting engines are hosted by a program or component that can conjure up an Active Scripting site. Active Scripting depends upon bidirectional communication between the Active Scripting engine and the Active Scripting host, as many other COM-based technologies do. For scripting to work, the host needs to implement an interface named IActiveScriptSite so that the scripting engine has a way to call back to the host.
The scripting engine uses the host's IActiveScriptSite interface to call on the script site from time to time to perform three main functions. The first function gets information about the objects being scripted. The second function informs the site about changes in the state of the scripting engine. The third function informs the site when there's an error running the script. An Active Scripting host is responsible for instantiating one of the available scripting engines and instructing the engine to run a script. The host then adds script code to the Active Scripting engine and asks the engine to execute the code. The host also has the option of creating COM objects and adding them to the Active Scripting engine's namespace so that the objects may be used within the script code.

The ScriptControl Object

The ScriptControl Object Model

In addition to holding the Active Scripting site required by the scripting engine, the ScriptControl maintains its own internal object model. The object model consists of module and procedure collections (see Figure 3).

Figure 3 ScriptControl Object Model

The top-level object of the ScriptControl object model is the module. Most scripts are collections of procedures. For example, here's some VBScript code combining variable declarations and some procedures:

Notice that the IScriptModuleCollection behaves like a normal iterator expected by Visual Basic. It exposes IEnumVariant through the _NewEnum property, and has Item and Count properties. This means developers using the control within Visual Basic can use the module collection within a For. Next loop. The modules collection is made of objects implementing the IScriptModule interface, which is shown in Figure 4.
Notice that IScriptModule includes AddCode, Eval, Execute, and Run functions, just like IScriptControl. In addition, the IScriptModule interface exposes a Name property (the name of the module), an IDispatch pointer exposing the module's public functions, and a collection of procedures, just like IScriptControl. I'll look at managing the code shortly.

Procedures

The second layer within the ScriptControl's object model consists of procedures. Just as with modules, ScriptControl defines the procedures through a collection and an individual interface. Here's the IScriptProcedureCollection interface:

IScriptProcedureCollection simply provides functions for iterating through the collection of procedures. It doesn't include an Add function (as IScriptModuleCollection does). Instead, you add procedures to a module through the module's AddCode method.
Each procedure is described through the IScriptProcedure interface like so:

IScriptProcedure's Name property exposes the procedure's name. NumArgs exposes the number of the procedure's arguments, and HasReturnValue indicates whether you can assign the value returned by the procedure to the left side of an assignment.

ScriptControl Events

Besides the incoming functions described by the IScriptControl interface, the ScriptControl exposes two events to the container application via a dispatch interface named DScriptControlSource. These two events are the Timeout event and the Error event. The Timeout event occurs when the time specified in the Timeout property has elapsed. The Error event occurs when the scripting engine detects some sort of error.
When the client receives an Error event, the client can ask the ScriptControl for the latest error by accessing IScriptControl's Error property (sort of like the Win32® GetLastError function). After accessing the Error property, the client gets an Error object, which implements the IScriptError interface (see Figure 5). A brief description of the interface is seen in Figure 6. I'll revisit IScriptError shortly.

Using the ScriptControl

There are several ways to use the ScriptControl. Of course, the easiest way is to drop it into a Visual Basic-based program as an ActiveX control. When running the ScriptControl as an ActiveX control, you can put it right in your form and exercise the functions to your heart's content. To learn how to use the ScriptControl, see the article "Exploring the Microsoft Script Control" by Francesco Balena in the July 1999 issue of Microsoft Internet Developer.
If you're a C++ developer, the easiest way to use the ScriptControl is to insert it into your project using the Project | Add To Project | Components and Controls menu item. This causes Visual Studio® to go out, read the ScriptControl's type library, and create C++ class wrappers around the IScriptControl, IScriptModule, IScriptModuleCollection, IScriptProcedure, IScriptProcedureCollection, and IScriptError interfaces. Including the ScriptControl in your application via the component gallery yields six wrappers for the previously mentioned interfaces: scriptcontrol (.h and .cpp), scripterror (.h and .cpp), scriptmodule (.h and .cpp), scriptmodulecollection (.h and .cpp), scriptprocedure (.h and .cpp), and scriptprocedurecollection (.h and .cpp).
My sample program for this column is a simple dialog box that exercises the ScriptControl (see Figure 7). The application lets you add functions and procedures to a script, evaluate single expressions and statements, and add objects to the scripting namespace.

Adding Code and Objects

Including the control in your project (using the component gallery) automatically inserts the ScriptControl wrapper files into your project form. Just drop the control into your app (or create it programmatically), and you can pound away on the control. For example, adding code to the script is simply a matter of calling the wrapper class' AddCode method and feeding it a CString:

If you recall from the bare-bones implementation of scripting in the October 1999 issue of MSJ, you had to manually manage a list of named items. All that is now done by the ScriptControl. Figure 8 contains code that looks up an object's CLSID from a ProgID, creates the object, and then adds the object to the ScriptControl's namespace.

Iterating Through Procedures

Once you've added code to the scripting control, it's often useful to get a list of the procedures and functions added. You can do this through the IProceduresCollection available from each module. Figure 9 shows how to retrieve a list of the functions and procedures that have been added to the global module.

Executing Code

There are two ways to execute code within the main module. The first way is to call the ScriptControl's Run function. I'll look at doing that in a future column since MFC's ScriptControl wrapper doesn't support the function. Another reason for procrastinating is that Run uses a variable argument list.
The second way to execute code is to call the ScriptControl's Execute function. Be aware that this method precludes using arguments in your function and procedure signatures:

Catching Scripting Errors

Of course, not all scripts are created perfectly, and they'll have bugs and errors within them. The ScriptControl's Error object returns detailed information about what exactly went wrong within your script.
To implement error checking, simply set up an event handler for the Error event. Whenever the ScriptControl calls your application, just turn around and get the Error object from the ScriptControl. Figure 10 shows how to fetch error information from the ScriptControl. It shows one way of responding to the ScriptControl's error event. Figure 11 shows a message box displaying an error in the sample program.

Conclusion

Despite its limitations (such as restricted data types and generally lower performance), scripting has many advantages over compiled code. Scripting code is generally more flexible because you can easily change it on the fly and rerun it without recompiling everything. In addition, scripting codeâ€"which you'll often see in HTML and ASP pagesâ€"is readily available in the Internet computing environment.
In many cases, it's useful to add scripting to your application. For example, if your app performs some sort of simulation or modeling, scripting provides a way for users to program your application. In addition, scripting provides a great environment for stress and regression testing.
In Windows®, adding scripting capability to your application is more or less a matter of providing an ActiveScriptSite implementation and managing the script code (that is, managing the named objects). If you don't have time to write that plumbing code, the Microsoft ScriptControl provides the generic functionality, and is a really quick way to get scripting into your app.
In this column I discussed the structure of the ScriptControl and some ideas for using it within an MFC application. In a future column, I'll go over hosting the ScriptControl within an ATL-based application.
George Shepherd is an instructor with DevelopMentor and a Software Engineer at Stingray Software. George is coauthor of MFC Internals (Addison-Wesley, 1996) and Programming Visual C++ (Microsoft Press, 1998).*

Методы

Добавляет атрибуты и стили HTML, которые должны быть отображены в указанном элементе управления HtmlTextWriterTag. Этот метод используется в основном разработчиками элементов управления.

Вызывается после добавления дочернего элемента управления в коллекцию Controls объекта Control.

Уведомляет серверный элемент управления, что элемент XML или HTML был проанализирован, и добавляет элемент в серверный элемент управления объекта ControlCollection.

Копирует любой непустой элемент указанного стиля в элемент управления Веба, перезаписывая уже существующие элементы стиля. Этот метод, в основном, используется разработчиками элементов управления.

Применяет свойства стиля, определенные в таблице стилей страницы, к элементу управления.

Запускает трассировку во время разработки данных отрисовки.

Собирает сведения о серверном элементе управления и доставляет их свойству Trace, которое отображается при включенной на странице трассировке.

Задает для кэшированного свойства ClientID значение null .

Удаляет сведения о состоянии элемента управления для дочерних элементов управления серверного элемента управления.

Удаляет сведения о состоянии элемента управления и состоянии представления для всех дочерних элементов серверного элемента управления.

Удаляет сведения о состоянии представления для всех дочерних элементов серверного элемента управления.

Задает для свойства ClientIDMode текущего экземпляра элемента управления и любых его дочерних элементов управления значение Inherit.

Копирует не инкапсулированные объектом Style свойства из указанного серверного веб-элемента управления веб-сервера в элемент управления веб-сервера, откуда вызывается этот метод. Этот метод используется в основном разработчиками элементов управления.

Создает новый объект ControlCollection для хранения дочерних элементов управления (литеральных и серверных) серверного элемента управления.

Создает объект стиля, который используется внутри класса WebControl для реализации всех относящихся к стилю свойств. Этот метод используется в основном разработчиками элементов управления.

Привязывает источник данных к вызываемому серверному элементу управления и всем его дочерним элементам управления.

Привязывает источник данных к вызванному серверному элементу управления и всем его дочерними элементами управления с возможностью вызова события DataBinding.

Привязывает источник данных к дочерним элементам управления серверного элемента управления.

Включает серверный элемент управления для выполнения окончательной чистки до освобождения памяти.

Завершает трассировку во время разработки данных отрисовки.

Определяет наличие у серверного элемента управления дочерних элементов управления. Если дочерних элементов управления нет, они будут созданы.

Создает идентификатор для элементов управления, которые не имеют назначенного идентификатора.

Определяет, равен ли указанный объект текущему объекту.

Выполняет поиск серверного элемента управления с заданным параметром id в текущем контейнере именования.

Выполняет поиск в текущем контейнере именования серверного элемента управления с указанным id и целым числом, указанным в параметре pathOffset , который содействует поиску. Эту версию метода FindControl не следует переопределять.

Задает фокус ввода на элемент управления.

Возвращает данные времени разработки для элемента управления.

Служит хэш-функцией по умолчанию.

Возвращает URL-адрес, соответствующий набору параметров маршрута.

Возвращает URL-адрес, соответствующий набору параметров маршрута.

Возвращает URL-адрес, соответствующий набору параметров маршрута и имени маршрута.

Возвращает URL-адрес, соответствующий набору параметров маршрута и имени маршрута.

Будучи переопределенным в производном классе, возвращает объекты ScriptDescriptor для элемента управления.

При переопределении в производном классе, возвращает файлы скрипта для элемента управления.

Возвращает объект Type для текущего экземпляра.

Возвращает часть с префиксом свойства UniqueID указанного элемента управления.

Определяет наличие у серверного элемента управления дочерних элементов управления.

Возвращает значение, указывающее, регистрируются ли события для элемента управления или каких-либо дочерних элементов управления.

Определяет наличие у серверного элемента управления только текстового содержимого.

Восстанавливает сведения о состоянии элемента управления предыдущего запроса страницы, сохраненные методом SaveControlState().

Восстанавливает сведения о состоянии просмотра из предыдущего запроса, сохраненного с помощью метода SaveViewState().

Извлекает физический путь, к которому ведет виртуальный путь (абсолютный или относительный).

Создает неполную копию текущего объекта Object.

Копирует любой непустой элемент указанного стиля в элемент управления Веба, но не перезаписывает уже существующие элементы стиля. Этот метод используется в основном разработчиками элементов управления.

Определяет, передается ли событие серверного элемента управления вверх по иерархии серверных элементов управления пользовательского интерфейса страницы.

Вызывает событие OnPreRender(EventArgs) и регистрирует элемент управления скриптом с элементом управления ScriptManager.

Возвращает Stream, используемое для чтения файла.

Присваивает родительскому элементу управления все источники события и сведения о них.

Вызывается после удаления дочернего элемента управления из коллекции Controls объекта Control.

Порождает событие Render(HtmlTextWriter) и отправляет содержимое серверного элемента управления предоставленному объекту HtmlTextWriter, который записывает содержимое для отображения в окне браузера.

Выводит открывающий HTML-тег элемента управления в указанное средство записи. Этот метод используется в основном разработчиками элементов управления.

Выводит содержимое дочерних элементов серверного элемента управления в предоставленный объект HtmlTextWriter, который записывает это содержимое для подготовки к просмотру на клиенте.

Выводит содержимое элемента управления в заданный модуль записи. Этот метод используется в основном разработчиками элементов управления.

Выводит содержимое серверного элемента управления в указанный объект HtmlTextWriter и сохраняет сведения о трассировке элемента управления, если трассировка включена.

Выводит серверный элемент управления в указанный объект HtmlTextWriter, используя указанный объект ControlAdapter.

Отображает закрывающий HTML-тег элемента управления в указанное средство записи. Этот метод используется в основном разработчиками элементов управления.

Возвращает адаптер элемента управления, отвечающий за отрисовку определенного элемента управления.

Возвращает URL-адрес, который может использоваться браузером.

Преобразует URL-адрес в адрес, доступный для клиента.

Сохраняет любые изменения состояния серверного элемента управления, произошедшие после отправки страницы обратно на сервер.

Сохраняет любое состояние, которое было изменено после вызова метода TrackViewState().

Задает данные времени разработки для элемента управления.

Назначает делегата обработчика событий для преобразования серверного элемента управления и его содержимого для просмотра в родительский элемент управления.

Задает данные трассировки для трассировки данных отрисовки во время разработки, используя ключ данных трассировки и значение данных трассировки.

Задает данные трассировки для трассировки данных отрисовки во время разработки, используя трассируемый объект, ключ данных трассировки и значение данных трассировки.

Возвращает строку, представляющую текущий объект.

Заставляет элемент управления отслеживать изменения в состоянии его представления, чтобы их можно было сохранить в свойстве ViewState объекта.

Remarks

The ScriptControl base class tests the page for a ScriptManager control during the PreRender stage of the derived control. The ScriptControl base class also makes sure that the derived control calls methods of the ScriptManager control to register script during the Render event. This includes registering ScriptDescriptor objects for the ScriptControl when the Render method is called. The Render method makes sure that ScriptDescriptor objects are not rendered unless the ScriptControl itself is rendered. This enables a ScriptControl to work inside a closed WebPart control.

You can add as many descriptors and types as necessary to any class that you derive from ScriptControl.

События

Происходит при привязке серверного элемента управления к источнику данных.

Происходит при инициализации серверного элемента управления, который находится на первом этапе его жизненного цикла.

Происходит при загрузке серверного элемента управления в объект Page.

Происходит после загрузки объекта Control, но перед отрисовкой.

Происходит при выгрузке серверного элемента управления из памяти.

Явные реализации интерфейса

Возвращает атрибуту веб-элемента управления указанное имя.

Задает атрибуту веб-элемента управления указанное имя и значение.

Описание этого члена см. в разделе ControlBuilder.

Описание этого члена см. в разделе GetDesignModeState().

Описание этого члена см. в разделе SetOwnerControl(Control).

Описание этого члена см. в разделе UserData.

Описание этого члена см. в разделе DataBindings.

Описание этого члена см. в разделе HasDataBindings.

Описание этого члена см. в разделе Expressions.

Описание этого члена см. в разделе HasExpressions.

Описание этого члена см. в разделе AddParsedSubObject(Object).

При переопределении в производном классе, регистрирует объект ScriptDescriptor для элемента управления.

При переопределении в производном классе, регистрирует файлы скрипта для элемента управления.

Methods

Adds HTML attributes and styles that need to be rendered to the specified HtmlTextWriterTag. This method is used primarily by control developers.

Called after a child control is added to the Controls collection of the Control object.

Notifies the server control that an element, either XML or HTML, was parsed, and adds the element to the server control's ControlCollection object.

Copies any nonblank elements of the specified style to the Web control, overwriting any existing style elements of the control. This method is primarily used by control developers.

Applies the style properties defined in the page style sheet to the control.

Begins design-time tracing of rendering data.

Gathers information about the server control and delivers it to the Trace property to be displayed when tracing is enabled for the page.

Sets the cached ClientID value to null .

Deletes the control-state information for the server control's child controls.

Deletes the view-state and control-state information for all the server control's child controls.

Deletes the view-state information for all the server control's child controls.

Sets the ClientIDMode property of the current control instance and of any child controls to Inherit.

Copies the properties not encapsulated by the Style object from the specified Web server control to the Web server control that this method is called from. This method is used primarily by control developers.

Creates a new ControlCollection object to hold the child controls (both literal and server) of the server control.

Creates the style object that is used internally by the WebControl class to implement all style related properties. This method is used primarily by control developers.

Binds a data source to the invoked server control and all its child controls.

Binds a data source to the invoked server control and all its child controls with an option to raise the DataBinding event.

Binds a data source to the server control's child controls.

Enables a server control to perform final clean up before it is released from memory.

Ends design-time tracing of rendering data.

Determines whether the server control contains child controls. If it does not, it creates child controls.

Creates an identifier for controls that do not have an identifier assigned.

Determines whether the specified object is equal to the current object.

Searches the current naming container for a server control with the specified id parameter.

Searches the current naming container for a server control with the specified id and an integer, specified in the pathOffset parameter, which aids in the search. You should not override this version of the FindControl method.

Sets input focus to a control.

Gets design-time data for a control.

Serves as the default hash function.

Gets the URL that corresponds to a set of route parameters.

Gets the URL that corresponds to a set of route parameters.

Gets the URL that corresponds to a set of route parameters and a route name.

Gets the URL that corresponds to a set of route parameters and a route name.

When overridden in a derived class, returns the ScriptDescriptor objects for the control.

When overridden in a derived class, returns the script files for the control.

Gets the Type of the current instance.

Returns the prefixed portion of the UniqueID property of the specified control.

Determines if the server control contains any child controls.

Returns a value indicating whether events are registered for the control or any child controls.

Determines if the server control holds only literal content.

Restores control-state information from a previous page request that was saved by the SaveControlState() method.

Restores view-state information from a previous request that was saved with the SaveViewState() method.

Retrieves the physical path that a virtual path, either absolute or relative, maps to.

Creates a shallow copy of the current Object.

Copies any nonblank elements of the specified style to the Web control, but will not overwrite any existing style elements of the control. This method is used primarily by control developers.

Determines whether the event for the server control is passed up the page's UI server control hierarchy.

Raises the DataBinding event.

Raises the Init event.

Raises the Load event.

Raises the OnPreRender(EventArgs) event and registers the script control with the ScriptManager control.

Raises the Unload event.

Gets a Stream used to read a file.

Assigns any sources of the event and its information to the control's parent.

Called after a child control is removed from the Controls collection of the Control object.

Raises the Render(HtmlTextWriter) event and sends server control content to a provided HtmlTextWriter object, which writes the content to be rendered to the browser.

Renders the HTML opening tag of the control to the specified writer. This method is used primarily by control developers.

Outputs the content of a server control's children to a provided HtmlTextWriter object, which writes the content to be rendered on the client.

Renders the contents of the control to the specified writer. This method is used primarily by control developers.

Outputs server control content to a provided HtmlTextWriter object and stores tracing information about the control if tracing is enabled.

Outputs server control content to a provided HtmlTextWriter object using a provided ControlAdapter object.

Renders the HTML closing tag of the control into the specified writer. This method is used primarily by control developers.

Gets the control adapter responsible for rendering the specified control.

Gets a URL that can be used by the browser.

Converts a URL into one that is usable on the requesting client.

Saves any server control state changes that have occurred since the time the page was posted back to the server.

Saves any state that was modified after the TrackViewState() method was invoked.

Sets design-time data for a control.

Assigns an event handler delegate to render the server control and its content into its parent control.

Sets trace data for design-time tracing of rendering data, using the trace data key and the trace data value.

Sets trace data for design-time tracing of rendering data, using the traced object, the trace data key, and the trace data value.

Returns a string that represents the current object.

Causes the control to track changes to its view state so they can be stored in the object's ViewState property.

Extension Methods

Returns the data source that is associated with the data control for the specified control.

Returns the field template for the specified column in the specified control's naming container.

Constructors

Initializes a new instance of the ScriptControl class in a derived class.

Читайте также: