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.
Related
I need to use JS variable to request particular item from array that stored in model. How to do this?
Here's a code sample:
function CreateCategoryList()
{
var limit = #(Model.CategoriesCount.ToString());
for (i=0; i<limit; i++)
{
var category = '<div class="CategoryItem">' + '#(Model.CategoryList[i].Name.ToString())' + '</div>';
$("#CategoriesPopup").append(category);
}
alert($(".CategoryItem:first").text());
}
I need to get access to i-th item in Model.CategoryList using i variable in for loop.
Razor is not executed on the client side, so your code sample above is invalid.
Easiest solution is to store the entire array as a client side Javascript variable, using serialization. I have used Json.NET in the example below.
I'd suggest you explore what gets executed on the server, and what gets executed on the client side. It will help your understanding when writing Views.
function CreateCategoryList()
{
var limit = #(Model.CategoriesCount.ToString());
var clientSideArray = JSON.parse('#(JsonConvert.SerializeObject(Model.CategoryList))');
for (i=0; i<limit; i++)
{
var category = '<div class="CategoryItem">' + clientSideArray[i] + '</div>';
$("#CategoriesPopup").append(category);
}
alert($(".CategoryItem:first").text());
}
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 have PrintTest.aspx page load images paths from database and render it in div to print these images maybe up to 20000 image .
for (int i = 0; i < Files.Count; i++)
{
HtmlImage image=new HtmlImage();
image.ID="ImageAN"+i.ToString();
image.Src=Files[i].ToString();
image.Alt="PrintImage";
image.Attributes.Add("class","PrintImage");
div_Print.Controls.Add(image);
}
Then call JavaScript function to print the content of div_Print
this.ClientScript.RegisterStartupScript(this.GetType(), "ClientScript", " PrintContent('div_Print')", true);
java-script function >
<script type="text/javascript">
function PrintContent(divName) {
var DocumentContainer = document.getElementById(divName);
var WindowObject = window.open();
WindowObject.document.writeln(DocumentContainer.innerHTML);
WindowObject.document.close();
WindowObject.focus();
WindowObject.print();
WindowObject.close();
}
</script>
But this scenario causes my browser keep crashing and closed.
I want any scenario to avoid this or print images without render it inside HTML
You don't . This is why people invented pagination and search.
And there are several reasons why:
Memory is a limited resource, especially on mobile devices (if you support them)
TMI, people cannot visually understand 20k images put on a single page, without spending hours staring at it
Something like this
public ControlsTypeHere PrintImages(int take, int skip)
{
int filesPrinted;
for (int i = skip; i < Files.Count; i++)
{
if(filesPrinted >= take)
break;
HtmlImage image=new HtmlImage();
image.ID="ImageAN"+i.ToString();
image.Src=Files[i].ToString();
image.Alt="PrintImage";
image.Attributes.Add("class","PrintImage");
div_Print.Controls.Add(image);
filesPrinted++;
}
return div_Print.Controls;
}
I am working on a donations website. In my page, I have a textbox which accepts a numeric value from the user (that is, money to be donated).
In my code-behind, I have a method which checks whether the value in the textbox is numeric. The method generates an error message if the number is invalid.
I also have a JavaScript which, after checking that the value in the textbox is numeric, opens a new tab to the website confirmation page, thanking the user for his donation. Here is the code of the javascript:
<script type="text/javascript">
function Open_Window()
{
var textbox = document.getElementById('DonationTextBox');
if (textbox.value != "")
{
if (isNan(textbox) == false)
{
window.open("DonationConfirmation.aspx")
}
}
}
</script>
The problem is that the tab is NEVER opened, even if the number is valid. Can you please help me solve this problem? Thank you.
P.S.
Here is the code of the button that initiates the validation:
<asp:ImageButton ID="PayPalButton2" runat="server" ImageAlign="Middle"
ImageUrl="Resources/Icons/PayPalCheckOut.gif"
onclick="PayPalButton2_Click" OnClientClick="Open_Window()"/>
The function name is isNaN. Note: The final 'N' is capital. That should solve your problem.
<script type="text/javascript">
function Open_Window()
{
var textbox = document.getElementById('<%=DonationTextBox.ClientID%>');
if (textbox.value != "" && !isNaN(textbox.value)) {
window.open("DonationConfirmation.aspx");
}
}
</script>
edit
instead of isNan should be isNaN (javascript is casesensitive)
Shouldn't this line...
if (isNan(textbox) == false)
be this instead...
if (isNan(textbox.value) == false)
First, I would recommend explicitly parsing the number, not relying on the implicit ToNumber operation that will be applied when you pass a string into isNaN. Presumably your users are inputting decimal, so if it's meant to be a whole number (e.g., 10), use:
var num = parseInt(textbox.value, 10);
If it's meant to be a number with a fractional component (e.g., 10.5), use:
var num = parseFloat(textbox.value);
You probably want parseFloat for a currency value.
Then your if condition becomes isNaN (note that the final N is capped) on num:
<script type="text/javascript">
function Open_Window()
{
var textbox = document.getElementById('DonationTextBox');
var num = parseInt(textbox.value, 10);
if (!isNaN(num))
{
window.open("DonationConfirmation.aspx")
}
}
</script>
And lastly, are you sure that the client-side ID of the textbox really is 'DonationTextBox'? ASP auto-generates client-side IDs, you may need to use ClientID instead, e.g.:
var textbox = document.getElementById('<%=DonationTextBox.ClientID%>');
Here is a stripped down working jsFiddle example:
http://jsfiddle.net/pjgalbraith/QZeSF/
The html:
Open
<textarea id="donationTextBox">1</textarea>
And the js:
function openWindow() {
if($('#donationTextBox').val() && isNaN($('#donationTextBox').val()) === false)
window.open("http://www.google.com/", "mywindow");
}
$(document).ready(function() {
$('#PayPalButton2').click(function(){
openWindow();
});
});
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...