I try to create COM Component for C# method and then try to access this method using javascript.
I have run GACUtil -i and Regasm /Codebase command for create share assembly and also register into Registry successfully.
This is my C# Method that return an int[] array for this I create an COM Component for this method.
nChannelsCount = 15 which is use in for loop
[Guid("4794D615-BE51-4a1e-B1BA-453F6E9337C4")]
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(IComOjbect))]
public class MyComObject : IComOjbect
{
}
[Guid("4B3AE7D8-FB6A-4558-8A96-BF82B54F329C")]
[ComVisible(true)]
public interface IComOjbect
{
[DispId(0x10000009)]
int[] GetData(int index);
}
But when I access this method in javascript it gives me and just count of 15 but I want 5500 count that show in Quick Watch. I dont know how to do this in javascript to achive this code but still i try this javascript code as below
<html>
<head>
<title>My Com Component</title>
<object id="myComComponent" name="myComComponent" classid="clsid:4794D615-BE51-4A1E-B1BA-453F6E9337C4">
</object>
<script language="javascript" type="text/javascript">
function MyComComponent_onload()
{
try {
var nAllData = [];
for (var index = 0; index < 15; index++)
{
nAllData.push(myComComponent.GetData(index));
}
alert(nAllData.length);
}
catch (err) {
alert(err.message);
}
}
</script>
</head>
<body onload="MyComComponent_onload();" onunload="MyComComponent_onunload();">
</body>
</html>
GetData returns an array. The JavaScript code calls it 15 times, and every time pushes the result onto yet another array, called nAllData (the fact that the variable name in JavaScript is the same as in C# is irrelevant - they are unrelated). As a result, you have an array of 15 elements, where each of those elements is in turn an array (presumably of 5500 elements - whatever GetData returns).
The loop within GetData implementation is pointless - the function returns on the very first iteration through that loop. It's not clear what you were trying to achieve there.
Finally, I don't believe JavaScript can directly consume safearrays (which is how I believe the return value of GetData ends up being represented by COM interop). Try this:
var data = new VBArray(myComComponent.GetData(index)).toArray();
alert(data.length);
nAllData.push(data);
Related
I want to use two arrays from C# in the JS snippet in a view. In order to do so I've tried to use the JavaScriptSerializer() but the data array isn't getting any values (the view's source shows it as follows):
var mydata =
Every example I've come across injects the C# code in JS by using <%=%> tags. This doesn't yield any results for me since I'm using ASP.NET MVC 4. Therefore I tried it with the following:
<script type="text/javascript">
var mydata = #{ new JavaScriptSerializer().Serialize(Model.GetData());}
$(function () {
// Generates a chart using the mydata array
}
</script>
What's wrong about this syntax? When I try to add an array for the headers underneath it, I receive a compilation error. There are warnings that the lines aren't terminated, but when I add ; at the end of each line it gives a syntax error as well (no specific error, just 'syntax error').
The data in GetData() and GetHeaders() are defined as such:
public List<int> GetData() {
return new List<int>(new[] { 4, 5, 6});
}
I've tried returning it as a int[] but this made no difference.
How can I use a C# list/array in a JavaScript snippet?
Edit: image of the unknown compilation error.
When I don't place the semicolons I get a syntax error on the second var. I get a suggestion to terminate the line endings, which adds the semicolons to the end. Then I have the issue as shown below. Curious detail: there are no red bars to the side of the file that usually indicate where the error is located.
That being said: when executing the script, the arrays have their expected values and everything works as it should.
The problem is that #{ } creates a block of code, it doesn't print the result to the rendered page. You can do this:
#{
var serializer = new JavaScriptSerializer();
#serializer.Serialize(Model.GetData())
}
Or even better, use the Json helper:
#Json.Encode(Model.GetData())
When you enclose operations within code blocks the output won't be rendered unless you explicitly tells it to render.
Try this one:
#Html.Raw(Json.Encode(Model.GetData()))
Try to put the result of the serializer in single quotes, like:
<script type="text/javascript">
var data = '#{ new JavaScriptSerializer().Serialize(Model.GetData());}';
</script>
You can create a HTML helper to call this, example:
<script type="text/javascript">
var data = '#Html.JSSerializerHelper(Model.GetData())';
</script>
Only one way that I think most elegant.
You could convert your List into JavaScript array to use within js.
Try this:
<script type="text/javascript">
var mydata = [];
#foreach(int i in Model.GetData()) {
<text>mydata.push(#i);</text>
}
$(function () {
// Generates a chart using the mydata array
}
</script>
I am using the below code to store data using jstorage. i can;t understand what is load_data_from_server(). Please help me to call a code behind function from jstorage
<script src="prototype.js"></script>
<script src="jstorage.js"></script>
<script>
// Check if "key" exists in the storage
var value = $.jStorage.get("key");
if(!value){
// if not - load the data from the server
value = "hai";
value = load_data_from_server() //I want to call c# code behind function here
// and save it
$.jStorage.set("key",value);
}
</script>
I Created an Com Component in C# and try to access in Javascript.
My C# Method is
Class myComComponent
{
private int[] nAllData;
public int[] GetArray(int index)
{
//Some Logic here that will return integer type of array{1,12,15,48,1452,45}
return nAllData;
}
}
call it from javascript but it gives me an type mismatch error.
Javascript Code
function MyComComponent_onload() {
try {
var nAllData = new Array();
for (var i = 0; i<= 5; i++)
{
nAllData.push(myComComponent.GetArray(i));
}
}
catch (err)
{
alert(err.message);
}
}
<html>
<head>
<object id="myComComponent" name="myComComponent" classid="clsid:4794D615-BE51-4A1E-B1BA-453F6E9337C4">
</head>
<body onload="MyComComponent_onload();">
//// Html Code goes here
</body>
<html>
JavaScript can only use the Automation-compatible subset of COM. Arrays of integers are not part of that subset.
You need to return a SAFEARRAY of VARIANT to be compatible with JavaScript, or alternatively return an object with the IEnumVariant interface (so foreach works), and IDispatch with an indexed default property (so indexing with square brackets works).
Okay, I've created an array in c# and want to access the values in a javascript for loop. Here's my global c# variables:
protected int count;
protected string[] arr = new string[20];
From there I add string values to the array in, let's say, the Page_Load() event.
And here's my ideal javascript code:
var count = <%= count %>;
for (var i = 0; i < count; i++)
{
document.write(<%= arr[i] %>);
}
Now if I were to just use arr[0] that would pop up with the correct information for arr[0], so I know I've got that part right, but is there a way to use that javascript variable "i" inside the <%= %> tag?
The ASP.NET parts of the code execute on the server. JavaScript is executed in the browser. The server just sees the JavaScript as text, it is meaningless and non-functional. Only when the browser receives the page and interprets the JS is it executed.
Remember, the server and the client PC are two different systems connected by a network. If you want to process data from system A on system B, you need to send the data to B.
If you want to send the data in the array to the browser so it can use it in some JavaScript, you need to serialize the array.
Something like this:
var myArray = <% = new JavaScriptSerializer().Serialize(serverSideArray) %>;
for(var i = 0; i < myArray.length; i++) {
document.write(myArray[i]);
}
Hope it is useful to you...
It was run fine in my test
<script language ="javascript">
var count = <%= count %>;
alert(count);
<%
for(int i=0;i<count;i++){
%>
document.write(<%= arr[i] %>);
<%}%>
</script>
Sadly, I don't think so; because the Javascript is evaluated at run-time in the browser, but the server block is evaluated at compile time on the server.
You can probably just expand the scope of your server block and just loop through arr in C#
I am going to get flamed for this, but here goes:
Server-side:
protected void Page_Load(object sender, EventArgs e)
{
string[] arr = new string[] { "1", "2", "3" };
StringArr = string.Join(",", arr.Select(a => string.Format("\"{0}\"", a)).ToArray());
}
protected string StringArr;
Client-side:
<script language="javascript" type="text/javascript">
var arr = [<%=StringArr %>];
alert(arr.length);
</script>
Let the ridicule begin.
I have this JS function :
var i = 0;
for (i = 0; i < myArray.length; i++) {
alert(myArray[i]);
}
but myArray[] is create on server side with c# :
ArrayList myArray = new ArrayList();
protected void Page_Load(object sender, EventArgs e)
{
foreach (MyObject myobject in MyObjects)
{
myArray.Add(myobject.Description);
}
}
so, how can I "pass" the C# array to Javascript? Or I need to print the whole javascript code on server side and send it to the server?
You can populate javascript array from serverside by using RegisterArrayDeclaration(arrayName, arrayValue) method.
In Cs file
RegisterArrayDeclaration("FavoriteNumbers", "1")
RegisterArrayDeclaration("FavoriteNumbers", "2")
RegisterArrayDeclaration("FavoriteNumbers", "3")
In javascript
<script language="javascript">
<!--
var FavoriteNumbers = new Array(1, 2, 3);
// -->
</script>
You could create json object(array) that would be serialized and sent to client where you can work with it as with Javascript array.
You can use
using System.Web.Script.Serialization;
JavaScriptSerializer serializer = new JavaScriptSerializer();
var output = serializer.Serialize(your_anon_object);
from
System.Web.Extensions.dll
You can serialize your C# array as JSON. You can read in detail about it here.
Also I would suggest using List<> instead of ArrayList.
You can use PageMethods to access functions in your code behind. Simply create a function to access your property.
Example here, http://www.dotnetspider.com/resources/21456-Page-Method.aspx
at before...
1)I will put a hidden in the page...
2) general a string like
"['a','b','c']"
into the hidden at .cs
3) cast to the array from the string at javascript
var arr = eval(hiddenvalue);
4) use it as a array...