Implementing the onchange event of a file upload control in C# without using automatic triggering

I am currently working on a web page that involves a file upload controller for images.

 <img src='#' id='imageId' alt='your image' height='64' width='64' src='placeholder.png' class='placeholder' >

 <input type='file' id='myID' onchange='previewImage(this)' accept='image/*' data-thumbnail='imageId'>

The HTML code above is converted from my existing asp code.

Now, I am trying to manually generate these two components using C# coding. Here's how I started:

    System.Web.UI.WebControls.Image preview = new System.Web.UI.WebControls.Image();
    preview.ID = "imageId";
    preview.Height = 64;
    preview.Width = 64;

    FileUpload tt = new FileUpload();
    tt.ID = "myID";

However, there are some attributes in the original HTML code that I am unsure how to implement with C# code.

I also need to handle the "onchange" event of the File upload control, which triggers the javascript function 'previewImage(this)' to preview the selected image.

Please assist me in figuring out how to achieve these tasks using C# code.

Answer №1

Give this a shot,

tt.Attributes.Add("onchange", "displayPreviewImage()");

Answer №2

Hopefully this information proves useful:

tt.Attributes["onchange"] = "previewImage(this)";

Answer №3

If you're looking for a solution, try this out...

javascript

<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script> 

<script type="text/javascript">
        function displayImage(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader(); 

            reader.onload = function (e) {
            $('#imageId').attr('src', e.target.result);
            };
            reader.readAsDataURL(input.files[0]);
        }
      }
 </script>  


<img src='#' id='imageId' alt='your image' height='64' width='64' class='placeholder' >
<input type='file' id='myID' onchange='displayImage(this)' >

To implement this in c#

ScriptManager.RegisterStartupScript(this, this.GetType(), "Javascript", "javascript:displayImage(input); ", true);

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

Unable to send emails through PHP

I am attempting to send an email using a PHP form. Below is the PHP code, including validation: <?php /* * Contact Form Class */ header('Cache-Control: no-cache, must-revalidate'); header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); ...

Comparing the use of Next.js static assets from the public folder with cloud-based storage solutions

Typically, in Next.js (or React) cloud-based storage solutions are commonly utilized for storing media files such as images. My inquiry is, what prevents us from saving images as static assets in the public folder and accessing them directly in our appli ...

Error message: "The property is not found within the specified type when using the OR operator with

Within my Angular component, I am faced with a challenge involving an Input that can be one of two types. @Input() profile: UserProfileDetails | BusinessProfileDetails; The structure of the profile template is straightforward and I want to avoid duplicati ...

Utilizing an array in handlebars template: A step-by-step guide

Recently, I encountered a challenge with passing a simple array variable to my Handlebars template. Here is an example of the array: var terms = ["1 year", "2 years"] I attempted to pass this variable to the template like so: var template = Handlebars.c ...

Experiencing difficulty adjusting the width of a Tumblr post with JavaScript or jQuery?

Calling all coding experts! I've been working on customizing a Tumblr theme, and everything is looking good except for one issue. I'm struggling to adjust the width of photos on a permalink (post) page. Check out this link: You'll notice t ...

Efficient Tracking: Triggering multiple inline OnClick events with just one click

I am looking to trigger multiple inline OnClick events with just one click. The first action is the Facebook share dialog box, which is working correctly. However, the second action where {ga(...) } triggers an event goal in Google (Universal) Analytics ...

Unique markers for Google Maps

I have been working on creating custom Google maps with the concept of incorporating 3 distinct markers such as forests, rivers, and lakes. While I have successfully added these custom markers using a helpful tutorial, I am now facing a challenge with sor ...

Tally the values entered into the text input field

I am interested in counting the number of IDs within an input of type "text" The values return like this: 1, 4, 6, etc. <input type="hidden" class="selected_ids" value="selected_ids" name="selected_ids[]" multiple="yes" id="selected_ids" /> ...

What is the most effective method for transferring and accessing data within a child form component?

This is how I am currently handling it: Parent.vue: // Template <form-child :schema="schema"><form-child> // JS data () { return { schema: [{ // name: '', value: '', type: '' }, { //etc ... }] } } For ...

Tips for maintaining control in AngularJS, jQuery, or JavaScript

I offer multiple services that provide data, but they take time to execute. Is there a way in AngularJS or JQuery to retain control and execute code only after the other functions have finished? For example: function fun1(){ // many functions get data ...

Seamlessly Loading Comments onto the Page without Any Need for Refresh

I am new to JavaScript and I am trying to understand how to add comments to posts dynamically without needing to refresh the page. So far, I have been successful in implementing a Like button using JS by following online tutorials. However, I need some gui ...

Tips for efficiently transmitting 'text/event-stream' information through express.js

Looking to set up a basic server-sent-event functionality using express.js on the server side: index.js: const app = require('express')(); const index_html = require('path').join(__dirname, 'index.html'); app.get(&ap ...

sending parameters to a callback function that is listening for arguments

function setmclisten(message, sender, sendResponse) { console.log(data); if(message['type'] === 'startUp') { console.log(data); sendResponse(data) } } function QuarryToServer(){ chrome.runtime.onMessage.removeListener( ...

Jquery form calculation not matching up

I've been struggling to make this jQuery math function work with my form. The snippet works fine, but when I try to integrate it into the actual form, I can't seem to get it aligned properly to perform the required calculations. Any suggestions ...

The images are currently unavailable as they are being retrieved from the database

I am encountering an issue with displaying images. Initially, the images are posted and saved successfully in MongoDB. You can view it in the image belowhttps://i.sstatic.net/NatvV.png Then the images are fetched from the database and when displayed, the ...

Unable to verify the SignalR chat hub

I am currently in the process of developing a real-time chat application using ASP.NET Core 8 Web API, SignalR, and Angular. I have incorporated the new authentication system introduced in .NET 8 with token authentication into my project. Authentication f ...

ASP.NET Snippet

I have a project requirement where I need to dynamically add or remove sub-pages or page fragments with various controls like menus, buttons, and textboxes. The user should be able to select from a dropdown menu which type of fragment to add, whether it&ap ...

The method Request.GetFriendlyUrlFileVirtualPath() in ASP.NET WebForms does not return any value

Currently, I am working on a basic ASP.NET WebForms project with just a few pages, and I am interested in implementing friendly URLs for SEO purposes as well as for URL localization. As the project is built on .NET 4.5, I decided to try using the Microsoft ...

How to retrieve a refined selection of items

In my scenario, there are two important objects - dropdownOptions and totalItem https://i.sstatic.net/VreXd.png The requirement is as follows: If 12 < totalItems < 24, then display "Show 12, Show 24" If 24 < totalItems < 36, only show "Show ...

Reaching the maximum request threshold

Currently, I am facing an issue where users are able to upload files from the client side (using Angular 4) to the server (implemented with Spring Boot). The problem arises when a user attempts to upload more than 6 files at once. In such cases, Chrome uti ...