Trying To Cast An Object To Javascript []{}- C# Key Value Collection OR Dictionary Or
i'd like to better understand the issue of casting object to a name vs value collection say ...just if i could do it like that 1) does the java-script needs some fine tuning ? pac
Solution 1:
I gave your sample a try and noticed that the startPrt parameter is actually being received as an Array of Dictionary(string, object). Hence, if you make the AJAX call like this:
var hDate = [];
hDate.push({ key: "Name", value: Name });
hDate.push({ key: "City", value: City });
hDate.push({ key: "Country", value: Country });
hDate.push({ key: "SelctedClass", value: selectedRC });
$.ajax({
contentType: 'application/json; charset=utf-8',
url: 'MyPage.aspx/AddNewRecord',
type: 'POST',
data: JSON.stringify({ startPrt: hDate }),
success: success, // success callback
error: error // error callback
});
You can define your WebMethod like the follwoing to convert the startPrt parameter to a dictionary:
[WebMethod]
public static void AddNewRecord(object startPrt)
{
var dict = new Dictionary<string, object>();
foreach (Dictionary<string, object> pair in (Array)startPrt)
dict.Add((string)pair["key"], pair["value"]);
}
Solution 2:
The conventional approach would be to construct a plain javascript object, which can be used by jQuery.ajax(...)
without any pre-processing.
var hDate = {
"Name": $('#tbx_Name').val(),
"City": $('#tbx_City').val(),
"Country": $('#tbx_Country').val(),
"SelctedClass": $('#ChosenRandomClass').val()
};
ajaxUpdate("addNew", hDate);
In ajaxUpdate()
, the ajax expression will be something like this :
function ajaxUpdate(action, data) {
...
$.ajax({
url: '...',
data: data,
...
success: function(){
...
}
});
}
Thus the serialized data will made available to the server-side script of whatever flavour.
Post a Comment for "Trying To Cast An Object To Javascript []{}- C# Key Value Collection OR Dictionary Or"