Monday, June 3, 2024
Homepage · c#
 Popular · Latest · Hot · Upcoming
80
rated 0 times [  82] [ 2]  / answers: 1 / hits: 18475  / 14 Years ago, mon, september 20, 2010, 12:00:00

Please, help me to understand the following part of the code from the post JavaScript post request like a form submit



function post_to_url(path, params, method) {
....
for(var key in params) {
var hiddenField = document.createElement(input);
hiddenField.setAttribute(type, hidden);
hiddenField.setAttribute(name, key);
hiddenField.setAttribute(value, params[key]);

form.appendChild(hiddenField);
}
....


Does this mean that we could pass the Dictionary object to the JavaScript function (calling JavaScript function from Silverlight app) and it will generate the param string in the form of key=value&key2=value2&key3=value3 ?



For example, passing the following Dictionary:



Dictionary<string, decimal> postdata = new Dictionary<string, decimal>();
postdata[productID1] = 126504;
postdata[productID2] = 126505;


We get the function output: productId1=126504&productId2=126505 ?


More From » c#

 Answers
91

Depends what you mean by output. The function does not output anything directly. It creates a form and adds an input element for every key-value pair in the object. It then submits that form, and the browser internally generates that parameter string and POSTs it to the URL. If by output you mean posts to the server, then yes - that is what it does.



Regarding passing in objects from managed code (silverlight), it seems it is possible. Dictionarys will be marshalled to Javascript objects as long as the key is a string. You will be able to access the entries by using the regular javascript property notation (dictionary[key] or dictionary.key).



More reading regarding Dictionary marshalling.



Also, I may be wrong (my C# is a bit rusty), but wouldn't:



Dictionary<string, decimal> postdata = new Dictionary<string, decimal>();
postdata[productID] = 126504;
postdata[productID] = 126505;


be considered invalid? In Dictionarys, like Javascript Objects, all keys must be distinct, no?






If you just want the query string, coming up with a function to create a parameter/query string from a JS object is relatively easy.



For example:



function paramString(object) {
var strBuilder = [];
for (var key in object) if (object.hasOwnProperty(key)) {
strBuilder.push(encodeURIComponent(key)+'='+encodeURIComponent(object[key]));
}
return strBuilder.join('&');
}

paramString(postdata)
productID1=126504&productID2=126505

[#95570] Thursday, September 16, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lamarmaximiliand

Total Points: 388
Total Questions: 104
Total Answers: 104

Location: Oman
Member since Fri, Dec 23, 2022
1 Year ago
;