Sending Form Parameters to Web-service using Operations - c#

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.

Related

Pass 2 different data types with jQuery to HttpHandler

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;
}
}

ajax pass array to wcf service

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.

Post Json List of Object to webmethod in C#?

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
}

javascript : pass an array to WCF service (c#)

I am trying to send an array to a wcf service.
My javascript :
var listoffice = new Array();
var office1 = { officeid : "1", officename : "Bat Cave" };
var office2 = { officeid : "2", officename : "Robin House" };
listoffice[0] = office1;
listoffice[1] = office2;
$.getJSON("ContactService.svc/createnewAwesomeoffice", { listoffice: listoffice }, function (data) {
...
});
Here's the service :
public struct officetoadd
{
public string officeid;
public string officename;
}
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public void createnewAwesomeoffice(List<officetoadd> listoffice)
{
...
}
the problem is the listoffice(in the service) is always null. Am I missing something ?
I think you need to put RequestFormat as well in your WebGetAttribute... Also, you may want to try turning "officetoadd" into a class and decorate it with DataContract and DataMember Attributes.
[DataContract]
public class officetoadd
{
[DataMember]
public string officeid;
[DataMember]
public string officename;
}
[OperationContract]
[WebGet(RequestFormat - WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public void createnewAwesomeoffice(List<officetoadd> listoffice)
{
...
}
Ok, I found a solution by myself. I think this is pertinent to write it here, so it may help other people.
I simply had to convert my array to JSON with this :
var arrayjson = JSON.stringify(listoffice);
And then pass it to the WCF service :
$.getJSON("ContactService.svc/createnewAwesomeoffice", { listoffice: arrayjson }, function (data) {
...
});
Note: The JSON object is now part of most modern web browsers (IE 8 & above).

Deserialize Json string from MVC action to C# Class

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);

Categories

Resources