having problem in, from table i get data and passed it to wcf web service
first service
public string SaveDate(string data) {
JavaScriptSerializer json = new JavaScriptSerializer();
List < string[] > mystring = json.Deserialize < List < string[] >> (data);
return "saved";
}
Second get data and ajax call
$('#btnPaymentOk').click(function () {
var objList = new Array();
$("table#tblGridProductInformation > tbody > tr").each(function () {
if ($(this).find('td.Qty').text() != '') {
objList.push(new Array($(this).find('td.LocalSalesPrice').text(), $(this).find('td.Total').text()));
//objList.push(new Array("a", "b"));
}
});
$.ajax({
type: "POST",
url: "/WebPOSService.svc/SaveDate",
data: "{data:" + JSON.stringify(objList) + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
}
});
});
in pass look like
{data:[["1.00","1.00"],["0.60","0.60"],["0.40","0.40"]]}
json array
problem is not get data from service end
help me out
Create a DataContract:
[DataContract]
public class Data
{
[DataMember]
public List<string[]> data { get; set; }
}
Here's code I used to test it, and it worked.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace ConsoleApplication
{
[DataContract]
public class Data
{
[DataMember]
public List<string[]> data { get; set; }
}
internal class Program
{
private static void Main(string[] args)
{
string jsonTxt = "{data:[[\"1.00\",\"1.00\"],[\"0.60\",\"0.60\"],[\"0.40\",\"0.40\"]]}";
var deserialized = JsonConvert.DeserializeObject<Data>(jsonTxt);
//Use this if you don't want to use DataContract, but you will have to reference Newtonsoft.Json.Linq
List<string[]> fullDeserialized = JsonConvert.DeserializeObject<List<string[]>>(JObject.Parse(jsonTxt)["data"].ToString());
}
}
}
Also, I would recommend you use Newtonsoft library for serializing/deserializing JSON data. Don't forget to add a framework reference to System.Runtime.Serializiation if you haven't already.
Related
Is it possible to pass 2 data types to the HttpHandler in a Webhandler
$.ajax({
type: "POST",
url: "FileHandler.ashx",
contentType:false,
processData: false,
data: {
data: newData,
pathname:"~/pathname/"
},
success: function (result) {
alert('success');
},
error: function () {
alert("There was error uploading files!");
}
});
The RequestPayload in the POST is [object object], is there documentation on how I can parse that object?
Hi Create a new model with all the props including the pathname prop
public class HandlerModel
{
public datatype dataprop1 {get;set;}
public datatype dataprop2 {get;set;}
public datatype dataprop3 {get;set;}
public datatype dataprop4 {get;set;}
public string pathname {get;set;}
}
then in your ashx file
public class QueryStringHandler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
//set the content type, you can either return plain text, html text, or json or other type
context.Response.ContentType = "text/plain";
//deserialize the object
UserInfo objUser = Deserialize<HandlerModel>(context);
//now we print out the value, we check if it is null or not
if (objUser != null) {
context.Response.Write("Go the Objects");
} else {
context.Response.Write("Sorry something goes wrong.");
}
}
public T Deserialize<T>(HttpContext context) {
//read the json string
string jsonData = new StreamReader(context.Request.InputStream).ReadToEnd();
//cast to specified objectType
var obj = (T)new JavaScriptSerializer().Deserialize<T>(jsonData);
//return the object
return obj;
}
}
I am trying to post List of object (or array of object) to c# Webmethod. I am understanding how to receive as parameter in the method and convert into local List of object?.
for (var i = 0; i < usersInfo.length; i++) {
user = {
UserName : usersInfo[i].UserName,
Email : usersInfo[i].Email,
Status : status
};
users.push(user);
}
var results = "";
$('#lblError').val('');
if (users.length > 0) {
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'UserValidation.aspx/ShowResults',
data: "{'UsersInfo':'" + JSON.stringify(users) + "'}",
async: false,
success: function (data) {
results = data.d;
$('#lblError').val(results);
},
error: function (xhr, status, error) {
var exception = JSON.parse(xhr.responseText);
alert(exception.Message);
}
});
}
Code behind
[WebMethod]
public static void ShowResults(//Here how receive list object from javascript)
{
//convert parameter to List<UsersInfo>
}
public partial class UsersInfo
{
public string UserName { get; set; }
public string Email { get; set; }
public string Status { get; set; }
}
Try to replace this line
data: JSON.stringify({ UsersInfo: users}),
James you are the right track; you need to define the correct type for the ShowResults parameter so that the binding will work and bind the incoming json to your UsersInfo class.
Your UsersInfo class appears to be a simple POCO so should bind without any custom binding logic :
[WebMethod]
public static void ShowResults(List<UsersInfo> UsersInfo)
{
//No need to convert
}
I have Dictionary which will return from server, i converted it json string format as below:
public static class Extensions
{
public static string ToJson<T>(this T obj)
{
MemoryStream stream = new MemoryStream();
try {
DataContractJsonSerializer jsSerializer = new DataContractJsonSerializer(typeof(T));
jsSerializer.WriteObject(stream, obj);
return Encoding.UTF8.GetString(stream.ToArray());
}
finally
{
stream.Close();
stream.Dispose();
}
}
public static T FromJson<T>(this string input)
{
MemoryStream stream = new MemoryStream();
try {
DataContractJsonSerializer jsSerializer = new DataContractJsonSerializer(typeof(T));
stream = new MemoryStream(Encoding.UTF8.GetBytes(input));
T obj = (T)jsSerializer.ReadObject(stream); return obj;
}
finally
{
stream.Close();
stream.Dispose();
}
}
}
[WebMethod]
public string callme()
{
Dictionary<int, string> myObjects = new Dictionary<int, string>();
myObjects.Add(1, "This");
myObjects.Add(2, "is");
myObjects.Add(3, "cool");
string json = myObjects.ToJson();
return json;
}
so Result is:
{"d":"[{\"Key\":1,\"Value\":\"This\"},{\"Key\":2,\"Value\":\"is\"},{\"Key\":3,\"Value\":\"cool\"}]"}
How I parse that in jquery? I m trying this but not help
$.ajax({
type: "POST",
url: "web.asmx/callme",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg){
$.each(msg.d, function (i) {
$("#data2").append(i.Key + " " + i.Value + "<br/>");
});
}
});
You'll have to do this things before it works:
put a ScriptService attribute to your web service
put a ScriptMethod attribute in your web service
If you do so, you don't even need to parse create the JSON in the server yourself. The WS infrastructure will do it for you.
Then, simply use msg.d on the client site. It will be automatically deserialized from the JSOn string.
Look here Using jQuery to Consume ASP.NET JSON Web Services for what you need to do on client side.
Here you have a full working sample with client and server side.
Be aware that before ASP.NET 3.5 the response message brought the data directly. In 3.5 and later, the data is in the .d property of the message.
EDIT2: Easier way to do it
I made a mistake in the 1st edit: .asmx can't serialize a Dictionay as XML. So, when I tested the solution in the first edit via the .asmx page, I got an error. But JSON can serialize a Dictionary which has a string or an object as key.
So, you can use this class to convert your Dictionary<int,string> to Dictionary<string,string> using this generic class:
public class DictionaryConverter
{
public static Dictionary<string,TValue>
ConvertDictionary<TKey,TValue>(Dictionary<TKey,TValue> dict)
{
Dictionary<string,TValue> newDict
= new Dictionary<string, TValue>();
foreach(TKey key in dict.Keys)
{
newDict.Add(key.ToString(), dict[key]);
}
return newDict;
}
}
This class can convert any Dictionary with any key type to a Dictionary<string,Tvalue> dictionary, which can be serialized as JSON, but not as XML. It uses the key type toString() method to convert the key in string. This will work perfectly for int and many other types. This method could be extended to receive a delegate to convert the key to string if necessary.
On client side you get the same thing with this solution and the one in the firs edit. The advantage of the one in the first edit is that it can also support serialization to XML: you can invoke the method through the .asmx page, and use the WebMethod as a regualr XML WebMethod.
EDIT: Serializing Dictionary<> in .asmx web service:
The serializer used with asmx doesn't support serializing dictionaries for XML. You can create a custom class and convert your dictionary to a list of this custom class, which has a key and a value property (the serializer doesn't support serializing KeyValuePair or Tuple, either, so you must use your own class).
This class serves two purposes:
It's a class that can be serialized with the serializer used by asmx for JSON
Allows to convert a dictionary in a list of elements of the class
public class KeyValue<TKey, TValue>
{
public KeyValue()
{
}
public TKey Key { get; set; }
public TValue Value { get; set; }
public static List<KeyValue<TKey,TValue>> ConvertDictionary
(Dictionary<TKey,TValue> dictionary)
{
List<KeyValue<TKey, TValue>> newList
= new List<KeyValue<TKey, TValue>>();
foreach (TKey key in dictionary.Keys)
{
newList.Add(new KeyValue<TKey, TValue>
{ Key = key, Value = dictionary[key] });
}
return newList;
}
}
Your web method should look like this:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] // it's JSON by default
public List<KeyValue<int,string>> GetKeyValueList()
{
List<KeyValue<int, string>> list
= KeyValue<int,string>.ConvertDictionary(yourDictionary);
return list;
}
Notes:
you can use any method name instead of GetKeyValueList
the TKey, TValue must be the same types of your dictionary key and value.
On the client side you get an array of Objects with Key and Value properties, which can be accesed like this:
msg.d[0].Key
msg.d[0].Value
This is the jquery ajax call:
$(document).ready(function () {
$.ajax({
url: 'MyService.asmx/GetKeyValueList',
type: "POST",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (msg) {
// use msg.d array of objects with Key and Value
}
});
});
$.each(msg.d, function() {
$("#data2").append(this.Key + " " + this.Value + "<br/>");
});
Also, it appears that your serialization is not working correctly, as the response coming back isn't being entirely parsed into JSON. The contents of d shouldn't be a string, it should be an object/array.
Based on JotaBe answer above, I created this extension method:
public class KeyValue<TKey, TValue>
{
public TKey Key { get; set; }
public TValue Value { get; set; }
public KeyValue()
{
}
}
public static class KeyValue_extensionMethods
{
public static List<KeyValue<TKey, TValue>> ConvertDictionary<TKey, TValue>(this Dictionary<TKey, TValue> dictionary)
{
var keyValueList = new List<KeyValue<TKey, TValue>>();
foreach (TKey key in dictionary.Keys)
keyValueList.Add(new KeyValue<TKey, TValue> { Key = key, Value = dictionary[key] });
return keyValueList;
}
}
Which then allows me to consume it using {object}.ConvertDictionary() syntax. For example:
[WebMethod(EnableSession = true)] [Admin(SecurityAction.Demand)]
public List<KeyValue<Guid, string>> Data_GuidanceItems_FileMappings()
{
return TM_Xml_Database.GuidanceItems_FileMappings.ConvertDictionary();
}
The only way it worked for me was
var $nomeP = $("#<%= tbxBuscaJornalista.ClientID %>").val();
$.ajax({
url: "MyPage.asmx/MyMethod",
dataType: "json",
type: "POST",
data: "{ 'variableName': '"+$nomeP+"' }",
contentType: "application/json; charset=utf-8",
success: function (msg) {
$.each(msg.d, function (index, value) {
$("#somePanel").append(index + " " + value + "<br/>");
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + errorThrown + " XmlRequest: " + XMLHttpRequest);
}
});
Please notice the line data: "{ 'variableName': '"+$nomeP+"' }" which shows I had to enclose the variable name (same as expected in code-behind) and the value in single quotes. Otherwise it would not work. Also, I tried to iterate and use $(this).Key and $(this).Value but that wouldn't work either. I was forced to use the function (index, value) approach.
I have an Ajax call (for a HighChartsDB chart) in a WebForm application that calls a webservice, which uses a WebRequest to call an MVC action in another application which returns a JsonResult.
I manage to pass the data back to the ajax call but the data I get back is not parsed as a json object but just a string.
My class:
public class CategoryDataViewModel
{
public string name { get; set; }
public List<int> data { get; set; }
public double pointStart { get; set; }
public int pointInterval { get { return 86400000; } }
}
My ajax function called by the highcharts:
function getBugs(mileId) {
var results;
$.ajax({
type: 'GET',
url: 'Services/WebService.svc/GetData',
contentType: "application/json; charset=utf-8",
async: false,
data: { "mileId": parseInt(mileId) },
dataType: "json",
success: function (data) {
console.log(data);
results = data;
}
});
return results;
}
And finally my WebService
public class WebService : IWebService
{
public string GetData(int mileId)
{
string url = "http://localhost:63418/Home/GetWoWData?mileId=" + mileId;
WebRequest wr = WebRequest.Create(url);
using (var response= (HttpWebResponse)wr.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
var objText = reader.ReadToEnd();
return objText;
}
}
}
}
With this when I console.log(data) on the ajax call I get:
[{\"name\":\"Sedan\",\"data\":[30,30,30,30,35],\"pointStart\":1307836800000,\"pointInterval\":86400000},{\"name\":\"Low\",\"data\":[800,800,800,826,1694],\"pointStart\":1307836800000,\"pointInterval\":86400000},{\"name\":\"Medium\",\"data\":[180,180,180,186,317],\"pointStart\":1307836800000,\"pointInterval\":86400000},{\"name\":\"High\",\"data\":[29,29,29,34,73],\"pointStart\":1307836800000,\"pointInterval\":86400000},{\"name\":\"Truck\",\"data\":[6,6,6,6,13],\"pointStart\":1307836800000,\"pointInterval\":86400000},{\"name\":\"SUV\",\"data\":[-172,-172,-172,-179,-239],\"pointStart\":1307836800000,\"pointInterval\":86400000},{\"name\":\"Convertible\",\"data\":[0,0,0,0,-404],\"pointStart\":1307836800000,\"pointInterval\":86400000},{\"name\":\"Limo\",\"data\":[-7,-7,-7,-8,-214],\"pointStart\":1307836800000,\"pointInterval\":86400000}]
I can't seem to manage to pass back into a proper Json object. I tried converting it back to my CategoryDataViewModel with this in my webservice:
var myojb = new CategoryDataViewModel ();
using (var response = (HttpWebResponse)wr.GetResponse())
{
using (var reader = new StreamReader(response .GetResponseStream()))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
myojb = (CategoryDataViewModel )js.Deserialize(objText, typeof(CategoryDataViewModel ));
}
}
return myojb;
But then I get Type 'Test.CategoryDataViewModel' is not supported for deserialization of an array.
Change:
myojb = (CategoryDataViewModel )js.Deserialize(objText, typeof(CategoryDataViewModel ));
to:
myojb = (List<CategoryDataViewModel> )js.Deserialize(objText, typeof(List<CategoryDataViewModel>));
and you should be fine. The array will de-serialize to a list no problem.
I've seen a similar thing before, I think you might need to change myObj to a list.
List<CategoryDataViewModel> myObjs = new List<CategoryDataViewModel>();
...
myObjs = js.Deserialize<List<CategoryDataViewModel>>(objText);
Client-Side I'm trying to capture the fields like this:
// Initialize the object, before adding data to it.
// { } is declarative shorthand for new Object().
var NewSubscriber = { };
NewSubscriber.FirstName = $("#FirstName").val();
NewSubscriber.LastName = $("#LastName").val();
NewSubscriber.Email = $("#Email").val();
NewSubscriber.subscriptionID = $("#subscriptionID").val();
NewSubscriberNewPerson.Password = "NewPassword1";
NewSubscriber.brokerID = "239432904812";
// Create a data transfer object (DTO) with the proper structure.
var DTO = { 'NewSubscriber' : NewSubscriber };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "NewSubscriberService.asmx/AddDigitalSubscriber",
data: JSON.stringify(DTO),
dataType: "json"
});
Now here's the problem I'm running into. How do I send these parameters and set them in the web service using C# or vb.net if it's easier? Any help is greatly appreciated
Here is what I have so far:
public class Service1 : System.Web.Services.WebService
{
public SubNameSpace.WebServiceSubBook.drmProfile _profile;
[WebMethod]
public string SetProfileData (object DTO) {
SetProfile (DTO);
}
[WebMethod]
public class SetProfileData (SubNameSpace.WebServiceSubBook.drmProfile _profile;) {
this._profile = _profile;
return "success";
}
}
}
SetProfile is an operation within the web service. SetProfileRequest is the message in the operation. I want to set certain parameters and then list other parameters in the code-behind file such as:
access_time = 30;
I'm completely lost...help!
Front-End Coder Lost in C# Translation
Your javascript object's first 'head' id NewSubscriber must match your web methods signature, for example:
you are calling url: "NewSubscriberService.asmx/AddDigitalSubscriber", with var DTO = { 'NewSubscriber' : NewSubscriber };
So you need something like this:
[WebMethod]
public string AddDigitalSubscriber(NewSubscriber NewSubscriber)
{
string status = string.Empty;
// Add Subscriber...
string emailFromJavascript = NewSubscriber.Email;
// do something
return status;
}
You will need a class in .NET like the following to match with your javascript object:
//... Class in .NET
public class NewSubscriber
{
public string FirstName;
public string LastName;
public string Email;
public int subscriptionID;
public string Password;
public string brokerID;
}
So the objects match and the names match.