Reputation: 1
How to set a C# variable to JavaScript array variable which is array.
Following choices
is array variable.m_lines
is c# array variable.
<script type="text/javascript">
$(document).ready(function () {
term = term.toLowerCase();
var choices = [];
choices = '<%= m_lines %>';
//var choices = ['aaaab', 'ActionScript', 'AppleScript', 'Asp', 'Assembly', 'BASIC', 'Batch', 'C', 'C++', 'CSS', 'Clojure', 'COBOL', 'ColdFusion', 'Erlang', 'Fortran', 'Groovy', 'Haskell', 'HTML', 'Java', 'JavaScript', 'Lisp', 'Perl', 'PHP', 'PowerShell', 'Python', 'Ruby', 'Scala', 'Scheme', 'SQL', 'TeX', 'XML'];
});
</script>
My actual requirement is to read a large text file (size approx 3 MB) and assign it to a JavaScript array variable. I'm not able to read file from client side and assign it to JavaScript variable, so reading at server side and trying it to assign to client side variable. each line of file is being used as array item.
Upvotes: 1
Views: 1373
Reputation: 343
Taking the script from your example, this could be:
<script type="text/javascript">
$(document).ready(function () {
term = term.toLowerCase();
var choices = [];
choices = <%= new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(m_lines) %>;
//var choices = ['aaaab', 'ActionScript', 'AppleScript', 'Asp', 'Assembly', 'BASIC', 'Batch', 'C', 'C++', 'CSS', 'Clojure', 'COBOL', 'ColdFusion', 'Erlang', 'Fortran', 'Groovy', 'Haskell', 'HTML', 'Java', 'JavaScript', 'Lisp', 'Perl', 'PHP', 'PowerShell', 'Python', 'Ruby', 'Scala', 'Scheme', 'SQL', 'TeX', 'XML'];
});
Or if this is a comma separated text file and is on the client side, you could read it using javascript, something like:
// <input name="myfile" id="myfile" type="file" />
$("#myfile").on('change', function () {
var file = this.files[0];
// Some validations
console.log(file.name);
console.log(file.size)
var FileReader = new window.FileReader();
reader.onload = function (event) {
// The file's text will be in event.target.result
//console.log(event.target.result)
var fileContentArray = event.target.result.split(/\r\n|\r|\n/g); // split by newlines
// Use the file content in fileContentArray
};
reader.readAsText(file);
});
See: https://developer.mozilla.org/en-US/docs/Web/API/FileReader
Upvotes: 0
Reputation: 218818
In a comment on the question, you define m_lines
as an array. One approach here could be to simply serialize that array to JSON:
choices = <%= JsonConvert.SerializeObject(m_lines) %>;
This is of course using the Newtonsoft JSON.NET library. You might also be able to use JavaScriptSerializer
(in System.Web.Script.Serialization
) otherwise.
Upvotes: 1
Reputation: 86
Try this -
var choices = <% if (m_lines!= null) {Response.Write(m_lines.ToString());}%>
Upvotes: 1