Show image depending on a data point within an ASP.NET GridView field

I am facing an issue with my gridview, specifically with the template field that contains an ASP image server tag. The goal is to display a different image in each row based on the value obtained during databind.

Unfortunately, my attempt to call a JavaScript function called GetImage() and pass the databind value to it has been unsuccessful. Here is a snippet of my code:

<Columns>
      <asp:TemplateField HeaderText="<%$Resources:LocalizedText,LabelStatus%>">
           <ItemTemplate>
                <asp:Image ID="imgStatus" runat="server" CssClass="label" src="GetImage(<%# Eval("Status_value") %>)"/>
           </ItemTemplate>
      </asp:TemplateField>
  </Columns>

The JavaScript function I've created looks like this:

function GetImage(value)
{
    if (value == 1)
    {
        return "../Images/act_green.gif";
    }
    else
    {
        return "../Images/act_red.gif";
    }
}

Can anyone help me identify what might be going wrong here? Any suggestions on how to resolve this issue would be greatly appreciated. Thanks!

Answer №1

If you don't have any additional requirements that haven't been mentioned, there's no reason to rely on Javascript. You can simply handle everything on the server side.

To update your asp:image tag, use the code snippet below:

<asp:Image ID="imgStatus" runat="server" CssClass="label" ImageURL='<%# GetImage((int)Eval("Status_Value")) %>' />

Add the following method in your code-behind:

public static string GetImage(int value)
{
    if (value == 1)
    { 
        return "../Images/act_green.gif";
    }
    else
    {
        return "../Images/act_red.jpg";
    }
}

That's it!

Answer №2

It appears that your GetImage function is not being run.

To troubleshoot, you can refer to this helpful link: IMG SRC tags and JavaScript


An alternative approach would be for the server side code to provide the image path directly instead of relying on JavaScript.

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

Unexpected behavior detected in three.js and raycaster where conditional else statements fail to execute

I immersed myself into the world of three.js with the help of YouTube tutorials designed for beginners. One particular tutorial caught my eye where they showcased three spheres floating in space, each clickable. Inspired by that, I delved deeper into crea ...

Having trouble with jQuery UI draggable when using jQueryUI version 1.12.1?

Currently, I am diving into the world of jQuery UI. However, I am facing an issue with dragging the boxes that I have created using a combination of HTML and CSS. My setup includes HTML5 and CSS3 alongside jQuery version 1.12.1. Any suggestions or help wou ...

Sending HTTP headers to a static directory in Connect (Node.js) can be achieved by manipulating the response object

Currently, I have a basic connect server set up to serve a directory. I am looking to add a custom HTTP header to all the files it serves. Below is my current code snippet: var connect = require('connect'); var app = connect() .use(conne ...

Leveraging the Request npm package synchronously within Meteor 1.3

In my Meteor 1.3.2.4 project, I tried utilizing the synchronous features of the request npm package. I initially followed the instructions provided in this guide article from Meteor and attempted to use Meteor.bindEnvironment. Here's the code: impor ...

Utilizing Vue 3 to transform an item within a list by referencing its index

Storing the element's index in a global variable is causing issues when trying to individually edit each of them. Adding multiple elements with similar properties but being unable to edit them separately due to alterations affecting the rest is a chal ...

Is there a way to customize the outlined color of an input adornment in MUI?

Looking to customize the default blue color in a Form Control outlined variant, but can't figure out how. I was able to do it with a regular TextField, but this one is a bit trickier. <FormControl variant="outlined"> < ...

Angular2 allows for the creation of global variables that can have their values updated throughout the

During the bootstrap process, I added a service to make use of global variables: bootstrap(AppComponent, [ GlobalService ]); global.service.ts import {Http} from 'angular2/http'; import {Observable} from 'rxjs/Observable'; import {O ...

Difficulties encountered when trying to load a corrupted CSV file using CsvHelper

Dealing with a .csv file that is separated by commas and has strings quoted with ''. The issue arises when there is a " or ' within the quoted text. Is there a solution to ignore these characters inside the quoted text? For example 'th ...

Using CasperJs in Node.js Child Process: Module 'casper' Not Found when using require statement

I'm having trouble understanding how 'require' works, as I can't seem to include CasperJS in a Node child process using the 'require' function. parent.js var exec = require('child_process').exec; for (var i = 0; i ...

Implement jQuery on Multiple Elements

My task involves populating a dynamically changing table with data that contains an unknown number of rows. Each row consists of a hyperlink, which when clicked, displays more details about that specific row. What I want to achieve is to attach a single j ...

Using Dynamic Queries in LINQ

Can Linq Queries be generated dynamically during runtime by utilizing an XML rule that can be converted into a Linq Query? ...

Creating a border around a panel while it is actively being scrolled

I encountered an issue while attempting to create a bordered panel. Initially, I set my properties panel to have: "AutoScroll = true;" and then added the border drawing codes in the Panel event: ControlPaint.DrawBorder(e.Graphics, ClientRecta ...

Managing a variety of tasks within the handleBeforeInput function in DraftJS

I'm stuck in a tricky situation where I need to change a block to an ordered list when the user presses '1.'. Below is the code snippet that achieves this: _handleBeforeInput(str) { if (str !== '.') { return false; ...

Can Google Maps be initialized asynchronously without the need for a global callback function?

Currently, I am working on developing a reusable drop-in Module that can load Google Maps asynchronously and return a promise. If you want to take a look at the code I have constructed for this using AngularJS, you can find it here. One issue I have enco ...

Leveraging the power of context to fetch data from a store in a React component within the Next

I'm having trouble with the title in my React project, and I'm new to React and Nextjs. When trying to fetch data from my dummy chat messages, I encountered this error: × TypeError: undefined is not iterable (cannot read property Symbol(Sy ...

Unable to retrieve the numerical value within the chart

I am a beginner in learning angularjs. I have implemented a contextmenu for displaying table data. <div contextmenu-container="meta.contextmenu"> <table class="table table-striped table-bordered report-table" fixed-header> ...

Guide on building a "like" button using a Node.js Express application

I am in the process of developing a website using node, express, and mongodb. I am facing an issue with passing a variable value from my ejs file to the server side. Can someone help me solve this problem? Here is what I have attempted so far: Example Ht ...

Guide to fetching a string using Angular's http client?

I am facing an issue with calling a server that returns a csv file as text. I am using Angular's HttpClient and I need to prevent it from trying to cast the csv file to JSON. I tried setting the responseType to 'text' in the httpOptions, but ...

The search results table does not exhibit the same behavior as the original table

I needed to enable the search function on my employee table, but encountered an issue when I implemented it - the search results were displayed on a separate page from the original table. To resolve this, I copied the table population code from the origina ...

Step-by-step guide on sending a JSON object to a web API using Ajax

I have created a form on my website with various fields for user entry and an option to upload a file. After the user fills out the form, my JavaScript function converts the inputs into a JSON file. I am attempting to send this generated JSON data along wi ...