Create JSON to send to server
Hi,
I managed to create something where I have an set of hidden inputs (all share the same class name)
The "id" of each is the date in a format of "yyyy_mm_dd".
The value of each input is empty.
When the user check a checkbox next to each entry (date) I bring up a dialog (text area), allow the user to enter something and then insert that text to the value of the hidden input.
When one "submit" the form (I prevent it though), I want to build up some kind of "array" of dates (that silly format I use as Id is ok) and and the text (if any) the user entered for that day and post it as JSON to a server side controller action (I used Asp.Net MVC)
I can get all the values I require now in my JavaScript code, but not sure how to build up a JSON object and have my controller action be able to process it though.
Any online sample would do the trick, unless someone feel like explaining.
Re: Create JSON to send to server
This uses jQuery ajax to submit a JAVASCRIPT object - converted to a JSON string - to a web service
Code:
function ctrlWebService(strOpt, strVal1, strVal2, strId) {
var objWebParam = {};
objWebParam.username = window.username || "";
objWebParam.ctrloption = strOpt;
objWebParam.ctrlval1 = strVal1;
objWebParam.ctrlval2 = strVal2;
var strWebParam = $.toJSON(objWebParam);
$.ajax({
type: "POST",
url: "WebService.asmx/CtrlService",
dataType: "json",
data: strWebParam,
contentType: "application/json; charset=utf-8",
success: function(msg) {
ajaxCtrlFinished(msg, strId, {});
},
failure: function(msg) {
ajaxCtrlFinished(msg, "failure", {});
},
error: function(msg) {
ajaxCtrlFinished(msg, "error", {});
}
});
}
The webservice is declared like this
Code:
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=False)> _
Public Function CtrlService(ByVal ctrloption As String, ByVal ctrlval1 As String, ByVal ctrlval2 As String, ByVal username As String) As String
If one of the object pairs was more complex then just a string value you can have the web service declared in these other various ways
Code:
Public Function AddService(ByVal toddtype As String, ByVal fromddtype As String, ByVal fromwho As String _
, ByVal objReturn As Dictionary(Of String, String) _
objReturn is a OBJECT datatype from the client side...
Code:
Public Function OperatorService(ByVal toddtype As String, ByVal fromddtype As String, ByVal fromwho As String _
, ByVal newkeys As IList(Of String) _
, ByVal updkeys As IList(Of String) _
, ByVal editkey As String _
, ByVal username As String _
, ByVal objReturn As Dictionary(Of String, String)) As String
newkeys and updkeys are ARRAYS of strings from javascript client side
Code:
, ByVal source As IList(Of Dictionary(Of String, String))
source is an ARRAY of JS OBJECTS.
That pretty much covers all the datatype combinations in JAVASCRIPT - all coming in as nice handy to use datatypes in VB.
Hope that was your question!!!