Controlling composites through the use of JavaScript functions

I am currently working on developing a composite control that implements IScriptControl.

Within the CreateChildControls() function, I have the following code snippet:

HtmlGenericControl ul = new HtmlGenericControl("ul");

HtmlGenericControl b2 = new HtmlGenericControl("li");
b2.Style["background-image"] = string.Format("url({0})", imageSrc);            
b2.Style["list-style"] = "none";
b2.Style["background-repeat"] = "no-repeat";
b2.Style["background-position"] = "center center";          
b2.Style["border-style"] = "none";
b2.Style["width"] = "20px";
b2.Style["height"] = "20px";
b2.Style["float"] = "left";
b2.InnerHtml = " ";


b2.Attributes["onmouseover"] = 
b2.Attributes["onmouseout"] =

ul.Controls.Add(b2);           
barContainer.Controls.Add(ul);

The objective is to assign the

b2.Attributes["onmouseover"]

and

b2.Attributes["onmouseout"]

attributes for JavaScript functions that are defined using the Prototype Model.

ProjectW.Edition.prototype = {
.
.
.

MouseOver: function(ctrl)
{
     DoWork...
},


MouseOut: function(ctrl)
{
     DoWork...
},

If necessary, make sure to include the following implementation for IScriptControl:

  
#region IScriptControl Implementation
        protected virtual IEnumerable<ScriptReference> GetScriptReferences()
        {           

            ScriptReference reference = new ScriptReference();
            reference.Assembly = "ProjectW";
            reference.Name = "ProjectW.EditonScripts.js";

            return new ScriptReference[] { reference };

        }


        protected virtual IEnumerable<ScriptDescriptor> GetScriptDescriptors()
        {
            ScriptControlDescriptor descriptor = new ScriptControlDescriptor("ProjectW.Edition", this.ClientID);


            descriptor.AddProperty(....);        

        );                       

            return new ScriptDescriptor[] { descriptor };                  
        }

        IEnumerable<ScriptReference> IScriptControl.GetScriptReferences()
        {
            return GetScriptReferences();
        }

        IEnumerable<ScriptDescriptor> IScriptControl.GetScriptDescriptors()
        {
            return GetScriptDescriptors();
        }

        #endregion

UPDATE: The HTML elements generated dynamically within CreateChildControls during runtime.

Answer №1

Why do you choose to use basic HTMLControls along with CompositeControl? It may be more efficient to utilize WebControl instead, especially if the control is constructed from these simple tags.

 public override void RenderContents(HtmlTextWriter writer)
 {
     writer.RenderBeginTag(HtmlTextWriterTag.Ul);

     writer.AddStyleAttribute(HtmlTextWriterStyle.BackgroundImage, "...");
     .
     .
     .
     writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID + "_Foo");
     writer.RenderBeginTag(HtmlTextWriterTag.Li);
     writer.Write("&nbsp;");
     writer.RenderEndTag();

     writer.RenderEndTag();

     base.RenderControl(writer);
 }

When adding event handlers in ASP.NET Ajax Enabled controls, there are some key differences to note. Make sure to assign a unique id to the target tag and attach the event accordingly, as demonstrated below.

ProjectW.Edition.prototype = {

    initialize: function()
    {
        base.callBaseMethod(this, "initialize");
        $addHandlers($get(this.get_id() + "_Foo"), "mouseover", Function.createDelegate(this, MouseOver));
    }

    dispose: function()
    {
        base.callBaseMethod(this,"dispose");
        $removeHandler($get(this.get_id() + "_Foo"), "mouseover", Function.createDelegate(this, MouseOver));
    }

    MouseOver: function(ctrl)
    {
        DoWork...
    },

    MouseOut: function(ctrl)
    {
        DoWork...
    }

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The eclipse android emulator does not support JavaScript and JQuery

<html> <head><title>XYZ</title> <!--<script src="jquery.gamequery-0.7.0.js"></script>--> <!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script ...

How can we ensure that the callback is called only after all functions have completed executing

I am a beginner when it comes to asynchronous programming. I have grasped the concept of using callbacks, but now I find myself needing to execute two functions asynchronously and only call my callback once they both complete: function bigFunction(data, c ...

Is it possible to showcase particular object values within an array rather than displaying them individually?

I have utilized an ajax call to fetch data from the Google Places API and implemented a for-in loop to extract the information. Although the desired information is being logged to the console, I am having trouble organizing it into an array as per my requi ...

What is the most efficient way to create multiple nested property objects in a shorter amount of time?

Currently, I am utilizing mongoDB for a data migration project where queries are written in plain JavaScript/JSON format: queryObj = {}; // main object passed to mongodb for queries The code snippet below is causing an error: queryObj[inObj.row]['$ ...

An error has occurred during parsing: An unexpected token was found, a comma was expected instead

I encountered an error while running my program (vue3 + element plus), and I'm unsure about the cause. Can someone please assist me? Below is the error description along with an image: 56:23 error Parsing error: Unexpected token, expected "," (11 ...

Click to cycle through an array in JavaScript

I've been attempting to loop through an array with the following code: var points = [ ['Point 0', 50, 91], ['Point 1', 50, 100] ]; for (i = 0; i < points.length; i++) { $('#' + i).click(function(i) { ...

Unable to dynamically append items to Owl Carousel using JavaScript

I am currently working on adding items dynamically to an Owl carousel. This is how I am approaching it: HTML <div id="avatar-carousel" class="owl-carousel lesson-carousel"> <div class="item item-logo"& ...

What is the best way to use a button element to update an h1 element in React.js?

I am currently working on a React application where I want to include a button that, when clicked, displays a joke generated from an npm package within an h1 element. Despite successfully installing the npm package (as indicated by my console log), I am st ...

What is the best way to populate all data in select2 (4.0) upon page load?

I'm currently utilizing the select2 plugin (v.4.0) and have a specific goal in mind: $("#search-input-chains").select2({ placeholder: "Unit", theme: "bootstrap4", ...

Introducing a fresh new feature incorporating various div elements through the power of JQuery

Why am I unable to retrieve the text of the newly added child divs? I am using JQuery to dynamically add these elements. Here is my sample fiddle: JSFIDDLE Could someone please guide me on what mistake I made? Javascript Code: var counter = 0; $("butto ...

Having trouble dynamically displaying the '<' symbol using JavaScript?

Whenever I attempt to show a string with the character '<' in it, the part of the string that comes after the symbol is not displayed. Strangely enough, when I output it to the console, it appears correctly. Take a look at this excerpt showcas ...

troubles with compatibility between bootstrap.css and IE11

I am currently developing a web application using AngularJS and bootstrap.css. While everything appears fine on Chrome, I am facing some formatting issues on both Firefox and IE11. HEAD <head> <meta charset="utf-8"> <meta http-equi ...

Oops! Looks like there's a hiccup with the express-validator plugin as the validation fails due to req.checkBody not being recognized as

Currently, I am setting up a post route to handle a submit request. The code snippet provided is from my user.js route: var express = require('express'); var router = express.Router(); var multer = require('multer'); var upload = multe ...

Tips for eliminating flicker upon the initial loading of a webpage caused by dynamic changes in CSS styles through JavaScript

Struggling with the load order of my CSS and JavaScript... Currently, I have a div with a blue background that is styled to appear sliced diagonally. However, upon initial page load (or CTRL+SHIFT+R), there's a brief moment where the slice effect doe ...

Create a button that, when clicked, redirects the user to a new page using a

Below is the server-side code snippet responsible for handling GET requests: app.get('/', function(req, res){ res.sendFile(__dirname + "/public/html/index.html"); }); app.get("/new-html", function(req, res){ console.log("Request /new-ht ...

Guide to setting up a search function with class name filtering

I am currently managing a website with multiple items, each represented by individual div elements. While all items share one common class name, they also have several other class names serving as tags to differentiate them (some tags may overlap between d ...

Having difficulties executing simple react code

I have a question that I feel silly asking, but I'm stuck and can't figure out what went wrong. This is a file with the extension .html. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" ...

Creating a clickable table row in bootstrap with optimal effectiveness

Is it better to implement a clickable row using jquery or pure JS? Consider server and client efficiency Ensure compatibility with various browsers The jquery option: // my tr (row) class <tr class='clickable-row' data-href='url:www.g ...

Converting an HTML table to a CSV file with pure JavaScript

I need to implement a CSV download feature on my website that converts the HTML table into downloadable content. While searching for a suitable plugin, I came across resources like http://www.dev-skills.com/export-html-table-to-csv-file/ which uses PHP s ...

When using a wildcard router in Node.js/Express.js, the static router may not be recognized

While using this specific route along with my other routes, I encounter an issue with serving static files: var public_dir = path.join(__dirname, 'public'); app.use('/public', express.static(public_dir)); However, when I add the follo ...