Reputation: 211
I have a very simple button click event in an ASP.Net application that calls a very simple javascript function to export the string of text passed to the function to a csv file. The button click event and the function it calls works perfectly if I pass it a raw string like this:
<button onclick="download_csv('TEST')">Download CSV</button>
However, if I pass a C# inline string variable like this, it breaks.
<button onclick="download_csv(<%=csvExport%>)">Download CSV</button>
This is the javascript function.
function download_csv(x) {
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(x);
hiddenElement.target = '_blank';
hiddenElement.download = 'pricing.csv';
hiddenElement.click();
}
The csvExport variable is declared in the .cs file behind the .aspx file and it is filled with a simple string of text; I've actually got it set to "Test" right now for testing. I've tried wrapping csvExport with single quotes, but that doesn't seem to work either. I must be missing something really simple.
Upvotes: 0
Views: 879
Reputation: 11775
Basically you're missing quotes around your text. You can debug this by using Chrome's dev tools to inspect the source of the page and see what .net is actually outputting.
Also, if your download link can ever contain user data, it's very important that you escape it to prevent XSS using HttpUtility.JavaScriptStringEncode
<button onclick="download_csv('<%= HttpUtility.JavaScriptStringEncode(csvExport) %>')">Download CSV</button>
Upvotes: 2
Reputation: 218960
it is filled with a simple string of text
Strings require quotes, whether in C# or in JavaScript. Your hard-coded example has them:
<button onclick="download_csv('TEST')">Download CSV</button>
But your dynamic example doesn't:
<button onclick="download_csv(<%=csvExport%>)">Download CSV</button>
Look at your generated page source to see the value:
<button onclick="download_csv(Test)">Download CSV</button>
And the resulting syntax error in your browser's development console. (Both of which should always be the first place you look. If you're not familiar with your browser's development tools, press F12 in Chrome. There is a lot of development and debugging capability there.)
I've tried wrapping csvExport with single quotes
You don't show that attempt, but from that description it sounds like you tried to do that in the server-side code. Which would just output the string value "csvExport"
but without quotes in your JavaScript code it would fail the same way for the same reason.
Just put your quotes back:
<button onclick="download_csv('<%=csvExport%>')">Download CSV</button>
Upvotes: 1