Sunday, July 31, 2011

ASP.Net Copy Contents To Clipboard

There are many problems with trying to accomplish this with ASP.  Most importantly, and code that you write in ASP.Net (Either C# or VB) do not communicate directly with the client.  Both VB and C# are interpreted at the server and converted into either HTML or Javascript at the server and then rendered to the client.  So the question is how do you get past the Framework in order to have access to the client’s clipboard?

Through the magic of the CLI (Common Language Infrastructure) when you finish your product and compile the code, the CLI takes over and converts the code into the CLR (Common Language Runtime).  Those that program in VB and especially those who program in C# will never admit that when you compile the code, both languages get compiled into the same language.  So in fact, whether you code in C# or VB, makes no difference and only controlled by preference. 

So again, how do we gain access to the client’s resources?  Well, considering the CLI takes our programming language (VB or C#) and converts it into HTML and Javascript (for ASP.Net anyways) we’ll have to resort to using a language that has access to the client and one that the client will interpret – JAVASCRIPT.  Let’s take a look at how to accomplish this.

We need a trigger to invoke our HTML and Javascript code, in this example we will use the onclick event of an ASP.Net button control.

Copy To Clipboard Example:

   1: <textarea id='txtCopyToClipboard' rows="3">This text will copy to your clipboard</textarea><br />    
   2:     <input type="button" id='btnCopy' onclick="clipboardData.setData('Text',document.getElementById('txtCopyToClipboard').value);"        value="Copy" />

Here we are accessing the textarea txtCopyToClipboard through the onclick Javascript event.  There is no postback because we did not identify the button with the runat property.  ASP.Net simply passes it through the compiler as HTML. 


So in the end, we are using classic HTML with Javascript 1.1 code.  Funny how we have to resort to yesterdays methods to accomplish today’s tasks.


Happy .Netting… Saleh

No comments:

Post a Comment