Invoke a JavaScript function with a parameter sourced from the ObjectDataSource by using the onClientClick event

I am facing a challenge in calling a javascript function within a Gridview. The javascript function in question is called display(id)

The id is a parameter retrieved from the Objectdatasource that binds my gridview, shown in the code snippet below:

<asp:ImageButton ID="imgbut" runat="server"  src="/images/gimage.jpg" OnClientClick="display('<%# Eval("id") %>')" />

This code fails to work due to the presence of double quotes inside the main set of double quotes.

An error message is displayed saying:

**

The server tag is not correct

**

I am currently seeking a solution to overcome this issue. Can anyone help me with a workaround?

Answer №1

Give this a try:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
    DataKeyNames="ID" CssClass="table" >
    <Columns>
        <asp:BoundField DataField="Fighter" HeaderText="Fighter"  />
        <asp:BoundField DataField="Engine" HeaderText="Engine"  />
        <asp:BoundField DataField="Thrust" HeaderText="Thrust"  />
        <asp:BoundField DataField="Description" HeaderText="Description" />
        <asp:TemplateField HeaderText="Preview">
            <ItemTemplate>
                <asp:ImageButton ID="cmdView" runat="server" 
                    ImageUrl = '<%# Eval("ImagePath") %>'  
                    Width="150"
                    OnClientClick='<%# "myrow(" + Eval("ID").ToString + ");return false" %>'
                    />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

<script>

    function myrow(rindex) {

        alert("Clicked row index: " + rindex)

    }

</script>

The code to load is as follows:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    If Not IsPostBack Then
        LoadGridF()
    End If

End Sub

Sub LoadGridF()

    Using conn As New SqlConnection(My.Settings.TEST4)
        Using cmdSQL As New SqlCommand("SELECT * FROM Fighters", conn)
            conn.Open()
            Dim rstData = New DataTable
            rstData.Load(cmdSQL.ExecuteReader)
            GridView1.DataSource = rstData
            GridView1.DataBind()
        End Using
    End Using

End Sub

And here is the output:

https://i.sstatic.net/gThkt.png

However, I often find such expressions a bit messy, so I like to create custom attributes for button clicks (or image button clicks).

For example, you can customize the click event like this:

<asp:TemplateField HeaderText="Preview">
    <ItemTemplate>
        <asp:ImageButton ID="cmdView" runat="server" 
            ImageUrl='<%# Eval("ImagePath") %>'  
            Width="150"
            OnClientClick='myrow(this);return false'
            MyRowIndex='<%# Container.DisplayIndex %>'                                                                        
            MyPKID='<%# Eval("ID") %>'                                                                        
            MyFighterName='<%# Eval("Fighter") %>'
            />
    </ItemTemplate>
</asp:TemplateField>

By adding these attributes, handling events becomes much simpler. Here's what happens when you click on the image now.

https://i.sstatic.net/kndbp.png

I also commonly apply this approach to server-side buttons.

You can then access the custom attributes like this:

Dim btn As Button = sender

Debug.Print(btn.Attributes("MyFigher").ToString)

Answer №2

Albert D.Kallal's solution was instrumental in resolving the issue I encountered. However, I made a slight modification by including quotation marks as separators before and after the value extracted from the database, as shown below:

<asp:ImageButton ID="imgbut" runat="server"  src="/images/gdrive.jpg" Width="20" OnClientClick='<%# "display(" + """" + Eval("IDRIVE").ToString + """);return false" %>' />

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

Delete the class once the image has finished loading

Is there a simple way to use JavaScript to implement Bootstrap 5 placeholders for lazy loading each image I load? Bootstrap 5 provides a placeholder class that displays a "loading card" while an image is loading. I want to utilize this class until each im ...

Using Vue3 to create a dynamic reference in a computed status, allowing for the repetition of a player multiple times in a table along with a play/pause

On the Vue3 page below, I have successfully integrated a player that displays a "play" icon when the player is stopped and a "pause" icon when it's playing. Now, my goal is to allow the player to repeat n times by placing it in a table. The challeng ...

Creating a factory pattern design to handle classes with varying input parameters

I'm searching for guidance on how to integrate the factory pattern into my program as it's a new concept for me. What would be the recommended approach for creating the factory and Execute() method that will trigger other methods with different p ...

Navigating through the concept of passing objects by reference in child components of Angular 2+

Understanding that TypeScript uses object passing by reference can be challenging, especially when dealing with deep copy issues. This becomes particularly cumbersome when working within a theme. I recently encountered an issue with a component containing ...

Discovering a User's Current Game on Discord.js: How Can You Find Out?

Hello, I'm attempting to implement a feature on my gaming server that automatically assigns roles based on the game people are playing. I've searched for a solution, but I seem to be at a standstill. Could someone please point out what mistake I ...

What benefits can be gained from utilizing the module pattern or objects to establish Angular components?

I'm contemplating the value of writing angular code in different ways. One way is like this: (function(angular, module) { 'use strict'; module.controller('MyCtrl', function($scope) { // maybe utilize helperFunction here ...

Steps to successfully retrieve an image using JavaScript on the client side while circumventing any CORS errors

I have a React application where I am displaying an image (an SVG) and I want the user to be able to download it by clicking on a button. The image is stored in Firebase Storage. However, I am encountering an issue with CORS error: Access to fetch at &ap ...

The cachedResponse does not contain any header information

I'm currently working on figuring out the age of a cached response by utilizing the date header of the response. I attempted to do this using a plugin that utilizes cachedResponseWillBeUsed. However, when trying to access cachedResponse.headers, I am ...

Oops! We're having trouble locating the react-redux context value. Make sure to wrap the component in a <Provider> to fix this issue. It's all about using Redux with

My debut Next.js website integrated with Redux is running into an issue with the following error: Error: could not find react-redux context value; please ensure the component is wrapped in a The setup involves using _document.js to establish a 'tem ...

Is it possible for me to interact with different elements upon hovering?

html, <div id="first"> <a>Click here</a> </div> <div id=second"> second div content </div> css, #first a:hover{ color:blue; /*change color on hover */ #second{ background:blue; } } In ...

ProgressMeterJS Plugin - Full-width Progress Bar

I have encountered a question regarding this particular plugin found at: My goal is to adjust the progress bar's width to 100% so it matches the width of its container. So far, I have made modifications to the plugin by changing the following line: ...

Executing a Python script within an ASP.NET application upon loading

I have a python script that scrapes a webpage for currency conversion. I successfully used this script in a previous php project and now need to adapt it for use in asp.net. In the past, I executed the python script using JavaScript by loading it on the h ...

Dispatching actions to update the Redux state is not reflecting any changes

Currently, I am developing a feedback board website and implementing a roadmap route where users can track website improvements. On mobile, I want to incorporate a three-section slide feature: planned, in-progress, and live stages. I found a useful code sn ...

Using the drop and drag features within a table cell

<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" /> <script src="http://code.jquery.com/jquery-1.8.2.js"></script> <script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script> & ...

Ng-repeat seems to be having trouble showing the JSON data

Thank you in advance for any assistance. I have a factory in my application that utilizes a post method to retrieve data from a C# function. Despite successfully receiving the data and logging it to the console, I am facing difficulties in properly display ...

The Axios GET method retrieves a response in the form of a string that represents an object

I have developed a function that triggers an axios Request. I am working with typescript and I am avoiding the use of any for defining return data types of both the function and the axios request itself. The issue arises when the returned object contains ...

javascript path as the first argument and callback as the last argument

Currently, I am in the process of creating a wrapper function for expressjs's app.get method. In these methods such as get, you can provide the path, some options, and then the callback. However, it is possible to omit the options and still have it w ...

Using Azure AD front-channel logout URL and SameSite cookie with ASP.NET

After exploring the possibility of implementing Azure AD for an older web forms ASP.NET application, I encountered a roadblock when attempting to utilize single sign out via the Front-channel logout URL in the App registration. The default setup was not f ...

accessing an ASP:TextBox in CodeFile

I am currently working on a page named Play.aspx, which has 2 ASP controls: <asp:TextBox ID="txtGuess" runat="server"></asp:TextBox> <asp:Button ID="Button1" runat="server" Text="Submit Guess" OnClick="PostGuess" /> At the top of my pag ...

Issues with knockout.js dropdown list not displaying correct binding when used within a foreach loop

I am facing an issue where, despite the absence of errors, I am struggling to display values in my drop-down list. Here is my knockout view model: function UserRecruitingViewModel(apiBaseUrl, userId) { var self = this; self.orgs = ko.observableArray(); / ...