Serializing a javascript array with Jquery - javascript

I have the following code:
<script type="text/javascript">
var checksSinceLastPostBack = new Array();
function clientSelectedIndexChanged(sender, eventArgs) {
var ajaxManager = $find("<%= RadAjaxManager.GetCurrent(Page).ClientID %>");
var serializedCheckData = checksSinceLastPostBack.serializeArray();
if (ajaxManager != null)
ajaxManager.ajaxRequest(serializedCheckData);
}
</script>
The
var serializedCheckData = checksSinceLastPostBack.serializeArray();
doesn't seem to work. Am I misunderstanding this?
Also if this works, how would I deserialize it in the code behind?
EDIT: Sorry, this is in ASP.NET

.serializeArray() is for serializing form elements with name/value pairs, not a normal Array. To convert that to a string you want something like:
var serializedCheckData = checksSinceLastPostBack.join(',');
...or some other delimiter. If you have more complex data you may want to go a JSON route.

Related

How to retrieve a specific object from a JSON value stored in sessionStorage?

I have this stored in the session:
What I'm looking to do is assign each object in the JSON as a variable so I can add them to the DOM appropriately.
This works but prints everything out:
if (sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9') != null) {
$(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9')).appendTo('.div');
}
What I'd like is something like this, but it doesn't work:
var div1 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'a.cart-contents')));
var div2 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'a.footer-cart-contents')));
var div3 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'div.widget_shopping_cart_content')));
Any help would be greatly appreciated. Thank you!
Getting the same value from the storage several times is not a good idea. In addition, you need better names for your variables.
var json = sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9');
if (json) {
var data = JSON.parse(json);
if (data) {
var cart_link = $(data['a.cart-contents']),
footer_link = $(data['a.footer-cart-contents']),
widget_div = $(data['div.widget_shopping_cart_content']);
}
}
So it appears you have set selectors as keys of the object so you could iterate those keys to get each selector.
The propose of those selector keys is not 100% clear. I am assuming that those selectors are the elements you want to insert the html strings into and that $() means you are using jQuery
if (sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9') != null) {
var data = JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9');
$.each(data, function(selector, htmlString){
$(selector).append(htmlString)
});
}

C# server array to client / javascript

This has probably been asked before but I can't seem to find any answers that I can get to work.
I have a SQL query that produces five rows of data in the backend.
And I then fetch the data from the query like so:
if (reader.HasRows) {
var list = new List < GetUserNames > ();
// Read advances to the next row.
while (reader.Read()) {
//Person p = new Person();
// To avoid unexpected bugs access columns by name.
//Convert.ToInt32(dataReader.GetValue(3));
wholeAvg = Decimal.Round(reader.GetDecimal(reader.GetOrdinal("wholeavg")), 2);
list.Add(new GetUserNames {
users = reader.GetString(2)
});
allRecords = list.ToArray();
}
}
Now what I would like to send to the client and use with javascript is the allRecords array.
Can someone point me in the right direction how to get the array from the backend?
Thanks!
You could serialize it to JSON then store the value in a hidden input. In your javascript you can then pick up the value of that field:
.cs:
var json = JsonConvert.SerializeObject(allRecords);
hdUsers.Value = json;
.aspx:
<asp:HiddenField runat="server" ID="hdUsers"/>
<script type="text/javascript">
var jsonString = $("[id$='hdUsers']").val()
var arr = JSON.parse(jsonString);
</script>
If you are using MVC, you can add 'allrecords' to TempData and use following code;
var records = #Html.Raw(Json.Encode(TempData["Records"]))

How to get json value by string?

I receive the following string from the server response:
var jsonData = '[{"firstName":"Bill","lastName":"Gates"},{"firstName":"George","lastName":"Bush"},{"firstName":"Thomas","lastName":"Carter"}]';
I see some jquery plugins can predefine the keys they want
like: index:"firstName", and they get a ul like
<li>Bill</li>
<li>George</li>
<li>Thomas</li>
If index:"lastName", they get a ul like
<li>Gates</li>
<li>Bush</li>
<li>Carter</li>
The only way I know how to parse a json format string is:
var object = JSON.parse(jsonData);
var firstName = object[i].firstName;
var lastName= object[i].lastName;
The plugin pass the index like a parameter
function f(index) {
return object[i].index;
}
How can they achieve this?
Thanks for helping!
You can access object properties with square brackets. JS objects work like arrays in this regard.
var objects = JSON.parse(jsonData),
key = "firstName";
objects.forEach(function (obj) {
var value = obj[key];
// ...
});

while using #htm.raw getting Syntax error "returns mark up that is not html encoded" [duplicate]

Vs'12 asp.net C# MVC4 - Int.Appl.Template EF Code First
Here is my very simple Script
<script class="TractsScript">
$('#Add').click(function (e) {
var val = #ViewBag.ForSection;
alert(val);
});
</script>
As per example I am wanting to simply set a variable in my script or USE a Viewbag. or Model.
I haven't been able to find an answer in any of the following forums: StckTrace1,StackTraceBetterAnswer
Other Things i have tried:
var model = #Html.Raw(Json.Encode(Model))
alert(model.Sections);
alert(#ViewBag.ForSection);
What you have should work. It depends on the type of data you are setting i.e. if it's a string value you need to make sure it's in quotes e.g.
var val = '#ViewBag.ForSection';
If it's an integer you need to parse it as one i.e.
var val = parseInt(#ViewBag.ForSection);
You can do this way, providing Json or Any other variable:
1) For exemple, in the controller, you can use Json.NET to provide Json to the ViewBag:
ViewBag.Number = 10;
ViewBag.FooObj = JsonConvert.SerializeObject(new Foo { Text = "Im a foo." });
2) In the View, put the script like this at the bottom of the page.
<script type="text/javascript">
var number = parseInt(#ViewBag.Number); //Accessing the number from the ViewBag
alert("Number is: " + number);
var model = #Html.Raw(#ViewBag.FooObj); //Accessing the Json Object from ViewBag
alert("Text is: " + model.Text);
</script>
try this method
<script type="text/javascript">
function set(value) {
return value;
}
alert(set(#Html.Raw(Json.Encode(Model.Message)))); // Message set from controller
alert(set(#Html.Raw(Json.Encode(ViewBag.UrMessage))));
</script>
Thanks
Use single quotation marks ('):
var val = '#ViewBag.ForSection';
alert(val);
When you're doing this
var model = #Html.Raw(Json.Encode(Model));
You're probably getting a JSON string, and not a JavaScript object.
You need to parse it in to an object:
var model = JSON.parse(model); //or $.parseJSON() since if jQuery is included
console.log(model.Sections);

Output a value in jQuery from Django

The value of 'content' is some parsed json. I want to now use this value in my query script. Bellow is what I have so far. The value needs to be in between var siteData = { } how can I do this?
What I have so far, but it does not work.
On my HTML Page:
<script type="text/javascript">
var temp = {{ content }};
</script>
In the builder.js:
$(document).on('pagebeforeshow', '#index', function (event) {
var siteData = {
temp;
}
});
this is the error:
**var temp = {"name":"dsaadsa","logo":"**
i think your variable temp has value, what you need.
if content equals "{a:1, b:2}", html under rendering will be var temp = {a:1, b:2};
and then you can write
$(document).on('pagebeforeshow', '#index', function (event) {
var siteData = temp; // window.temp
});
Django is escaping the JSON string try {{ content|safe }}
To expand a bit, Django offers all sorts of filters (of which 'safe' is one) that you can apply to variables you are outputting to templates.
Another example would be {{ content|lower }} to output lower case text.
The docs for this are here
Please post exact errors with full traceback, as they appear in Javascript console, without them is just a shot in the dark..
I believe you have incorrect syntax
var temp is global it will be accessible in builder.js, but siteData is invalid syntax for object literal; should be something like:
var siteData = { key: value}

Categories

Resources