Using a C# list in a javascript snippet - c#

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>

Related

Call C# code behind function from jstorage

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>

Javascript Com array Component giving me wrong array values

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);

HiddenField.value is undefined in JS

In my aspx markup I have the following defined:
<asp:HiddenField runat="server" ClientIDMode="Static" ID="hidField" />
I have C# code as follows, which gives my hidden field a value:
hidField.value = check().ToString();
assume that check is a function which returns true, for simplicity.
I made JS code to do the following:
_myBool = $("#hidField");
alert(_myBool.value);
This alerts undefined.
For debugging purposes, I stepped through and saw that in C#, hidField.value is indeed true.
And I tried alerting _myBool.length which returned 1 and _myBool which returned [Object object] so Im not calling undefined on undefined.
Try this
_myBool = $("#hidField"); //my bool is a jQuery Object
alert(_myBool.val()); //can only get value with .val()
OR
_myBool = $("#hidField")[0]; //[0] gets the element in the object
alert(_myBool.value); //can use the javascript .value
Missing $ symbol..
var _myBool = $("#hidField");
alert(_myBool[0].value); // DOM Object
alert(_myBool.val() ); // jQuery Object
Also note the selector might Not work with runat="server" attribute as it prepends the content placeholder..
This is a better selector
var _myBool = $('[id*="hidField"]');
You forgot the dollarsign and also use the val() function
alert($("#hidField").val());
Make sure you are using the right ID:
_myBool = $("#<%= hidField.ClientID %>").val();
View your source when the page loads and check for that field. Chances are the ID is not "hidField". The code above will be correct.

How can I cycle an array on javascript made on C#?

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...

Microsoft JScript runtime error: 'null' is null or not an object

I have application like where i can create dynamic tabs. and delete cross bar option on tabs. When I am trying to delete the tab I am getting error like
Microsoft JScript runtime error: 'null' is null or not an object and point to my Javascript code.
Here is my JS code.
<script type="text/javascript">
/* <![CDATA[ */
function deleteTab(tabText)
{
var tabStrip = $find("<%= RadTabStrip1.ClientID %>");
var multiPage = $find("<%= RadMultiPage1.ClientID %>");
var tab = tabStrip.findTabByText(tabText);
var pageView = tab.get_pageView();
var tabToSelect = tab.get_nextTab();
if (!tabToSelect)
tabToSelect = tab.get_previousTab();
tabStrip.get_tabs().remove(tab);
multiPage.get_pageViews().remove(pageView);
if (tabToSelect)
tabToSelect.set_selected(true);
}
/* ]]> */
</script>
and in page lode
if (!Page.IsPostBack)
{
RadTab tab = new RadTab();
tab.Text = string.Format("New Page {0}", 1);
RadTabStrip1.Tabs.Add(tab);
RadPageView pageView = new RadPageView();
pageView.Height = new Unit("50px");
pageView.Width = new Unit("1300px");
RadMultiPage1.PageViews.Add(pageView);
BuildPageViewContents(pageView, RadTabStrip1.Tabs.Count);
RadTabStrip1.SelectedIndex = 0;
}
This error can occur if you are trying to use an object which is null. In that code quite a lot of things can return null: $find, findTabByText, getPageView, get_nextTab, get_previousTab etc. I suggest you alert() everything before using it. That way you will find what is null.
You're not checking any of those function calls to see if they're actually returning something. One of them is returning null, but your code does not notice that and tries to use the result in a subsequent statement.
Try this in Firefox with Firebug and you'll probably get better error messages.
$find can return null if you are trying to call it too early. Remember that ASP.NET AJAX controls are created during the Sys.Application.Init event. If you try to access them earlier (e.g. in the window.onload) the $find() will not work.

Categories

Resources