ListView Dynamic Button with Javascript No Postback

Daniel 21 Reputation points
2022-07-27T10:39:59.687+00:00

Hi,

I'm trying to add a button control to my ListView control dynamically in code behind with some JavaScript functionality added. I have a panel control in my ListView in order to add the button dynamically in the ItemDataBound event.

pnlContent.Controls.Add(new LiteralControl("<button onclick='alert('Hello World!');return false;'>Test Button Code Behind</button>"));  

However although the buttons appears once the page has loaded the source code appears as:

<button onclick="alert(" hello="" world!');return="" false;'="">Test Button Code Behind</button>  

So the JavaScript is not functional due to the additional ="" being added after each space (not sure why this is happening?). I would really appreciate any help or pointers as to where I'm going wrong?

Many thanks,
Daniel

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,272 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,277 questions
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 26,136 Reputation points
    2022-07-27T12:22:56.433+00:00

    Use the following string format.

    pnlContent.Controls.Add(new LiteralControl(@"<button onclick=""alert('Hello World!');return false;"">Test Button Code Behind</button>"));  
    

    It is usually a bad idea to create dynamic controls in Web Forms due to how state management works in the framework. I would simply add the button HTML to the ListView and let the ListView handle the rendering.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Daniel 21 Reputation points
    2022-07-27T13:37:06.827+00:00

    The @ fixed it - thank you!

    0 comments No comments