How can I cycle an array on javascript made on C#? - 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...

Related

Pass List<int> from code behind to use in Javascript function

Currently I have a Javascript function that uses I can hard code values in like -
data: [1,4,7,9]
However I wish to pass in an integer list to set the values from the code behind something like -
C# Code Behind
public List<int> listOfInts = new List<int>();
protected void Button1_Click(object sender, EventArgs e)
{
listOfInts.Add(1);
listOfInts.Add(4);
listOfInts.Add(7);
listOfInts.Add(9);
ScriptManager.RegisterStartupScript(this, GetType(), "blah", "JSfunction()", true);
}
Aspx
data: <% = listOfInts %>
However this breaks with the error -
0x800a1391 - Microsoft JScript runtime error: 'JSfunction' is undefined
If I remove the aforementioned line and do it like this in the function (not passing anything from the code behind like I need to) -
var listOfInts = new Array();
listOfInts[0] = 1;
listOfInts[1] = 2;
listOfInts[2] = 3;
listOfInts[3] = 4;
and then set -
data: [listOfInts[0],listOfInts[1],listOfInts[2],listOfInts[3]]
This works fine. How can I pass the values from the code behind to populate the values in the Javascript function?
You need to format listOfInts as a javascript array. Try adding a property in your code-behind like this:
protected string IntsAsJSArray
{
get
{
return string.Format("[{0}]", string.Join(",", listOfInts));
}
}
Then in your ASPX page
data: <%= IntsAsJSArray %>
A more generic method to do this... and significantly better in my opinion would be to write something that works for any object you needed to do this for. Consider the following extension methods...
public static T FromJson<T>(this string jsonData, Encoding encoding = null)
where T : class
{
encoding = encoding ?? Encoding.Default;
var deserializer = new DataContractJsonSerializer(typeof(T));
var buffer = encoding.GetBytes(jsonData);
using (var stream = new MemoryStream(buffer))
{
return deserializer.ReadObject(stream) as T;
}
}
public static string ToJson<T>(this T obj, Encoding encoding = null)
where T : class
{
encoding = encoding ?? Encoding.Default;
var serializer = new DataContractJsonSerializer(typeof(T));
using (var stream = new MemoryStream())
{
serializer.WriteObject(stream, obj);
return encoding.GetString(stream.ToArray());
}
}
Usage then looks like this in your case...
data: <% = listOfInts.ToJson() %>
This works whether you have a List, Int[], or any other object for that matter on your asp.net side. Also don't forget to consider what encoding your JSON text is in.

Using a C# list in a javascript snippet

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>

How to read something from a file with C# and use it with HTML codes on ASP.NET page?

I'm doing a school project, I need to make a simple web site, add google maps on it, read, lets say, 100 diffrent addresses from a text file and show those locations on google maps with markers.
Now I'm trying to add google maps to my ASP.net page with javascript which I saw on google maps tutorials. And there's that problem which I have to convert adresses to coordinates. So for that I'm using
function addAddressToMap(response) {
if (!response || response.Status.code != 200) {
alert("Sorry, we were unable to geocode that address");
}
else {
place = response.Placemark[0];
point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
marker = new GMarker(point);
map.addOverlay(marker);
marker.openInfoWindowHtml(place.address + '<br>' + '<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode);
}
}
// showLocation() is called when you click on the Search button
// in the form. It geocodes the address entered into the form
// and adds a marker to the map at that location.
function showLocation() {
var address = "izmit";
var address2 = "ağrı";
geocoder.getLocations(address, addAddressToMap);
geocoder.getLocations(address2, addAddressToMap);
}
these functions and they are working fine. But my problem here is, I need to get these address informations from a text file. But to get them, I need to use a few diffrent codes. And I want to make it on the server side with C# codes. But I don't know how to write some codes on server side and then return something to HTML side as address. I hope you understand. Thank you for your helps.
Update:
Server code:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterArrayDeclaration("Skills", "'asa'");
Page.ClientScript.RegisterArrayDeclaration("Skills", "'bell'");
Page.ClientScript.RegisterArrayDeclaration("Skills", "'C'");
Page.ClientScript.RegisterArrayDeclaration("Skills", "'C++'");
}
}
Client side:
function showLocation()
{
var address = "izmit";
var address2 = "ağrı";
geocoder.getLocations(Skills[0], addAddressToMap);
}
Now if I use "asa" instead of Skills[0] it will show the location and mark, but with Skills[0] it's not working. And thank you for your answer that was what I'm looking for.
even if I try var MyValue = Skills[0]; and then use MyValue instead of Skills[0] it's still not working
If I understood your question correctly, you want to create an array on the server side and read it in the client.
See this link for a tutorial on how to pass an array from the server to the client.
Basically, you want to use the ClientScriptManager.RegisterArrayDeclaration method to add values to the array.
You can then easily read it in javascript.
Server Side:
string arrayName = "MyArray";
Page.ClientScript.RegisterArrayDeclaration(arrayName , "'value1'");
Page.ClientScript.RegisterArrayDeclaration(arrayName , "'value2'");
Javascript on Client Side:
function readArray()
{
for (var i = 0; i < MyArray.length; i++)
{
//Reading Element From Array
var myValue = MyArray[i];
}
}

Looping through values from c# array using javascript

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.

Persist data using JSON

I'm tryping to use JSON to update records in a database without a postback and I'm having trouble implementing it. This is my first time doing this so I would appreciate being pointed in the right direction.
(Explanation, irrelevant to my question: I am displaying a list of items that are sortable using a jquery plugin. The text of the items can be edited too. When people click submit I want their records to be updated. Functionality will be very similar to this.).
This javascript function creates an array of the objects. I just don't know what to do with them afterwards. It is called by the button's onClick event.
function SaveLinks() {
var list = document.getElementById('sortable1');
var links = [];
for (var i = 0; i < list.childNodes.length; i++) {
var link = {};
link.id = list.childNodes[i].childNodes[0].innerText;
link.title = list.childNodes[i].childNodes[1].innerText;
link.description = list.childNodes[i].childNodes[2].innerText;
link.url = list.childNodes[i].childNodes[3].innerText;
links.push(link);
}
//This is where I don't know what to do with my array.
}
I am trying to get this to call an update method that will persist the information to the database. Here is my codebehind function that will be called from the javascript.
public void SaveList(object o )
{
//cast and process, I assume
}
Any help is appreciated!
I have recently done this. I'm using MVC though it shouldn't be too different.
It's not vital but I find it helpful to create the contracts in JS on the client side and in C# on the server side so you can be sure of your interface.
Here's a bit of sample Javascript (with the jQuery library):
var item = new Item();
item.id = 1;
item.name = 2;
$.post("Item/Save", $.toJSON(item), function(data, testStatus) {
/*User can be notified that the item was saved successfully*/
window.location.reload();
}, "text");
In the above case I am expecting text back from the server but this can be XML, HTML or more JSON.
The server code is something like this:
public ActionResult Save()
{
string json = Request.Form[0];
var serializer = new DataContractJsonSerializer(typeof(JsonItem));
var memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(json));
JsonItem item = (JsonItem)serializer.ReadObject(memoryStream);
memoryStream.Close();
SaveItem(item);
return Content("success");
}
Hope this makes sense.
You don't use CodeBehind for this, you use a new action.
Your action will take an argument which can be materialized from your posted data (which, in your case, is a JavaScript object, not JSON). So you'll need a type like:
public class Link
{
public int? Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Url { get; set; }
}
Note the nullable int. If you have non-nullable types in your edit models, binding will fail if the user does not submit a value for that property. Using nullable types allows you to detect the null in your controller and give the user an informative message instead of just returning null for the whole model.
Now you add an action:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DoStuff(IEnumerable<Link> saveList)
{
Repository.SaveLinks(saveList);
return Json(true);
}
Change your JS object to a form that MVC's DefaultModelBinder will understand:
var links = {};
for (var i = 0; i < list.childNodes.length; i++) {
links["id[" + i + "]"] = list.childNodes[i].childNodes[0].innerText;
links["title[" + i + "]"] = list.childNodes[i].childNodes[1].innerText;
links["description[" + i + "]"] = list.childNodes[i].childNodes[2].innerText;
links["url[" + i + "]"] = list.childNodes[i].childNodes[3].innerText;
}
Finally, call the action in your JS:
//This is where I don't know what to do with my array. Now you do!
// presumes jQuery -- this is much easier with jQuery
$.post("/path/to/DoStuff", links, function() {
// success!
},
'json');
Unfortunately, JavaScript does not have a built-in function for serializing a structure to JSON. So if you want to POST some JSON in an Ajax query, you'll either have to munge the string yourself or use a third-party serializer. (jQuery has a a plugin or two that does it, for example.)
That said, you usually don't need to send JSON to the HTTP server to process it. You can simply use an Ajax POST request and encode the form the usual way (application/x-www-form-urlencoded).
You can't send structured data like nested arrays this way, but you might be able to get away with naming the fields in your links structure with a counter. (links.id_1, links.id_2, etc.)
If you do that, then with something like jQuery it's as simple as
jQuery.post( '/foo/yourapp', links, function() { alert 'posted stuff' } );
Then you would have to restructure the data on the server side.

Categories

Resources