Share via

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

Developer technologies | C#
Developer technologies | 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.

Developer technologies | ASP.NET Core | Other
0 comments No comments

Answer accepted by question author

  1. AgaveJoe 31,361 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.

    Was this answer helpful?

    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!

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.