I want to send JSON data to my WCF Service, but in the Service there is my object always null. I have read so many articles but I can't solve my problem.
[WebInvoke(UriTemplate = "/POST/PersonPost", Method = "POST",BodyStyle=WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
public Person InsertPerson(Person per)
{ Debug.WriteLine("InsertPerson");
if (per == null)
{
return new Person("2", "null");
}
Debug.WriteLine("POST:[PersonId = {0} PersonName = {1}]", per.Id, per.Name);
return new Person("1", "InsertPerson");
}
[DataContract]
public class Person
{
public Person(string id, string name)
{
this.id = id;
this.name = name;
}
[DataMember]
public string Id { get; set; }
[DataMember]
public string Name { get; set; }
public override string ToString()
{
var json = JsonConvert.SerializeObject(this);
return json.ToString();
}
}
and here my jQuery:
var person = {};
person.Id = "abc123";
person.Name = "aaaa";
var per = {};
per.per = person;
var param = JSON.stringify(per);
//param = "{"per":{"Id":"abc123","Name":"aaaa"}}"
$.support.cors = true;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: param,
dataType: "json",
processData: false,
crossDomain: true,
url: "http://localhost:59291/Person/POST/PersonPost",
success: function (data) {
alert("Post erfolgreich: ");
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Fehler Post: Status " + xhr.status + " AntwortText " + xhr.responseText);
}
});
What is there wrong? Why is my parameter per in the insertPerson method always null.
sorry my english, this work for me:
var LstPerson = new Array();
var person = {};
person.Id = 1
person.name = 'abc'
LstPerson.push(person)
var param = JSON.stringify(LstPerson);
send only [{"id": "1", "name": "abc"}] from JS, and WCF REST definition:
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json)]
public Person InsertPerson(List<Person> per)
The reason this is not working is because the DataMembers are id and name and not Id and Name. You need to modify the following code:
person.Id = "abc123";
person.Name = "aaaa";
var per = {};
per.per = person;
to
person.id = "abc123";
person.name = "aaaa";
var per = {};
per.per = person;
Your web site is breaking the Same Origin Policy
Heres Ways to circumvent the same-origin policy
Your setting crossDomain to true, but this is only compatible with jsonp, read this
Try this:
var person = {};
person.id = "1";
person.name = "abc";
var param = JSON.stringify(person);
One of the reasons, you are receiving your request object as null because, the method is expecting an object of type Person. This in JSON is as follows according to your definition of Person.
{"id": "1", "name": "abc"}
This is because there is nothing like per inside Person.
Person person = New Person("1", "abc");
person.per //There is nothing defined as per inside person.
Related
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've been using a hard coded JSON object:
var resuts = [{id: 1, Code: "Code A"}, {id: 2, Code: "Code B"}]
I'm then iterating this object calling the items by index and using .length:
for (var i = 0; i < resuts.length; i++) {
console.log('id:' + resuts[i].id + ' | ' + 'Code:' + resuts[i].Code}
Now I want to pull this data from the server so I created an object to handle the properties and have this action method:
public ActionResult GetResults()
{
string json = JsonConvert.SerializeObject(new
{
results = new List<Question>()
{
new Question { id = 1, Code = "Code A},
new Question { id = 1, Code = "Code B}
}
});
return Json(new { data = json }, JsonRequestBehavior.AllowGet);
}
I'm calling it with this AJAX:
function GetResultsJSON() {
$.ajax({
type: 'GET',
url: '/Home/GetResults/',
dataType: 'json',
traditional: true,
success: function (data) {
results = data;
},
error: function (data) {
alert('Error.');
}
})
};
Now my results object contains:
"{" results ":[{" id ":1," Code ":" Code A "},{" id ":1," Code ":" Code B "}]}"
Now I get JavaScript errors when trying to use the length property or call items by index. From what I have read up on, I think my original hard coded object is just an array, however, I have to work differently with the JSON that's returned from my controller.
Can anyone advise on either returning the array format that I was originally working with or the best way to handle the JSON format as it's returned here? I have tried things like
$.each(data, function(i, obj) {
alert(obj.name);
});
but this returns undefined. Any help would be great.
public JsonResult TestAjax(int leagueId)
{
var results = new List<BaseballViewModel>()
{
new BaseballViewModel{ DivisionId = 1},
new BaseballViewModel{ DivisionId = 2}
}.ToList();
return Json(results, JsonRequestBehavior.AllowGet);
}
$.ajax({
url: "/Home/TestAjax",
type: "GET",
data: { leagueId: 5 },
success: function (data) {
// alert(JSON.stringify(data)); show entire object in JSON format
$.each(data, function (i, obj) {
alert(obj.DivisionId);
});
}
});
Instead of:
$.each(data, function(i, obj) {
alert(obj.name);
});
why don't you try:
$.each(data.results, function(i, obj) {
alert(obj.name);
});
If you create a Model class that way :
[Serializable()]
public class MyResponse
{
public int Id {get; set;}
public string Code {get; set;}
}
And that you create a list of "MyResponse"
You will just have to do
return Json(new { data = listOfMyResponse}, JsonRequestBehavior.AllowGet);
Here is my code in Default.aspx:
$(function() {
var dataSource = {};
$("#MainTree,#SubTree").jstree({
"json_data": {
"ajax":{
type: "POST",
async: true,
url: "Default.aspx/GetJson",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function(msg) {
dataSource = msg;
},
error: function(err) {
alert(err);
},
data: dataSource,
},
},
"plugins": ["themes", "json_data", "ui", "dnd"]
});
});
And here is GetJson method in Default.aspx.cs:
[WebGet(ResponseFormat = WebMessageFormat.Json)]
[System.Web.Services.WebMethod]
public static string GetJson()
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
DataTable dtEmployee = new DataTable();
dtEmployee.Columns.Add("EmpId", typeof(int));
dtEmployee.Columns.Add("Name", typeof(string));
dtEmployee.Columns.Add("Address", typeof(string));
dtEmployee.Columns.Add("Date", typeof(DateTime));
//
// Here we add five DataRows.
//
dtEmployee.Rows.Add(25, "Rk", "Gurgaon", DateTime.Now);
dtEmployee.Rows.Add(50, "Sachin", "Noida", DateTime.Now);
dtEmployee.Rows.Add(10, "Nitin", "Noida", DateTime.Now);
dtEmployee.Rows.Add(21, "Aditya", "Meerut", DateTime.Now);
dtEmployee.Rows.Add(100, "Mohan", "Banglore", DateTime.Now);
foreach (DataRow dr in dtEmployee.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dtEmployee.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
EDIT:
This is the result when i check GetJson method respone:
{"d":"[{\"EmpId\":25,\"Name\":\"Rk\",\"Address\":\"Gurgaon\",\"Date\":\"\/Date(1372999726975)\/\"},{\"EmpId\":50,\"Name\":\"Sachin\",\"Address\":\"Noida\",\"Date\":\"\/Date(1372999726975)\/\"},{\"EmpId\":10,\"Name\":\"Nitin\",\"Address\":\"Noida\",\"Date\":\"\/Date(1372999726975)\/\"},{\"EmpId\":21,\"Name\":\"Aditya\",\"Address\":\"Meerut\",\"Date\":\"\/Date(1372999726975)\/\"},{\"EmpId\":100,\"Name\":\"Mohan\",\"Address\":\"Banglore\",\"Date\":\"\/Date(1372999726975)\/\"}]"}
And the result is nothing..It just appeared "..Loading" flashly and then it return blank page..please help me to show what's the problem here is..Thanks a lot.
It seems that you've not read the documentation properly so I would suggest you do that first.
When you use json_data plugin, you need to follow basic structure as shown below and could be found here, that means you need to provide Json data in below format:
{
"data" : "node_title",
// omit `attr` if not needed; the `attr` object gets passed to the jQuery `attr` function
"attr" : { "id" : "node_identificator", "some-other-attribute" : "attribute_value" },
// `state` and `children` are only used for NON-leaf nodes
"state" : "closed", // or "open", defaults to "closed"
"children" : [ /* an array of child nodes objects */ ]
}
Taking response structure into consideration, you need to have server side class as shown below:
public class Emp
{
public EmpAttribute attr { get; set; }
public string data { get; set; }
}
public class EmpAttribute
{
public string id;
public bool selected;
}
And your pagemethod should look alike below:
[WebGet(ResponseFormat = WebMessageFormat.Json)]
[System.Web.Services.WebMethod]
public static List<Emp> GetJson()
{
List<Emp> empTreeArray = new List<Emp>();
Emp emp1 = new Emp()
{
attr = new EmpAttribute(){ id= "25",selected=false},
data = "Nitin-Gurgaon"
};
Emp emp2 = new Emp()
{
attr = new EmpAttribute(){ id="50",selected=false},
data = "Sachin-Noida"
};
empTreeArray.Add(emp1);
empTreeArray.Add(emp2);
return empTreeArray;
}
Your clientside binding code should be like below:
$(function() {
var dataSource = {};
$("#demo1").jstree({
"json_data": {
"ajax":{
"type": "POST",
"url": "Default2.aspx/GetJson",
"contentType": "application/json; charset=utf-8",
"dataType": "json",
success: function(msg) {
return msg.d;
},
error: function(err) {
alert(err);
}
}
},
"plugins": ["themes", "json_data", "ui", "dnd"]
});
});
Notice return msg.d in Success function that is missing from your code.
More examples could be found here
Please go through documentation of any plugin you use next time.
type http://Default.aspx/GetJson directly in browser and check whether correct data is coming or not.
Other two locations where you can add debugging code is
success: function(msg) {
dataSource = msg;
},
error: function(err) {
alert(err);
}
add breakpoints and debug the javascript.
The response is encapsulated in a property called "d". Instead of datasource = msg you should have datasource = msg.d
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);
Can i use session values inside a WebMethod?
I've tried using System.Web.Services.WebMethod(EnableSession = true) but i can't access Session parameter like in this example:
[System.Web.Services.WebMethod(EnableSession = true)]
[System.Web.Script.Services.ScriptMethod()]
public static String checaItem(String id)
{
return "zeta";
}
here's the JS who calls the webmethod:
$.ajax({
type: "POST",
url: 'Catalogo.aspx/checaItem',
data: "{ id : 'teste' }",
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
}
});
You can use:
HttpContext.Current.Session
But it will be null unless you also specify EnableSession=true:
[System.Web.Services.WebMethod(EnableSession = true)]
public static String checaItem(String id)
{
return "zeta";
}
There are two ways to enable session for a Web Method:
1. [WebMethod(enableSession:true)]
2. [WebMethod(EnableSession = true)]
The first one with constructor argument enableSession:true doesn't work for me. The second one with EnableSession property works.
For enable session we have to use [WebMethod(enableSession:true)]
[WebMethod(EnableSession=true)]
public string saveName(string name)
{
List<string> li;
if (Session["Name"] == null)
{
Session["Name"] = name;
return "Data saved successfully.";
}
else
{
Session["Name"] = Session["Name"] + "," + name;
return "Data saved successfully.";
}
}
Now to retrive these names using session we can go like this
[WebMethod(EnableSession = true)]
public List<string> Display()
{
List<string> li1 = new List<string>();
if (Session["Name"] == null)
{
li1.Add("No record to display");
return li1;
}
else
{
string[] names = Session["Name"].ToString().Split(',');
foreach(string s in names)
{
li1.Add(s);
}
return li1;
}
}
so it will retrive all the names from the session and show.
You can try like this
[WebMethod]
public static void MyMethod(string ProductID, string Price, string Quantity, string Total)// Add new parameter Here
{
db_class Connstring = new db_class();
try
{
DataTable dt = (DataTable)HttpContext.Current.Session["aaa"];
if (dt == null)
{
DataTable dtable = new DataTable();
dtable.Clear();
dtable.Columns.Add("ProductID");// Add new parameter Here
dtable.Columns.Add("Price");
dtable.Columns.Add("Quantity");
dtable.Columns.Add("Total");
object[] trow = { ProductID, Price, Quantity, Total };// Add new parameter Here
dtable.Rows.Add(trow);
HttpContext.Current.Session["aaa"] = dtable;
}
else
{
object[] trow = { ProductID, Price, Quantity, Total };// Add new parameter Here
dt.Rows.Add(trow);
HttpContext.Current.Session["aaa"] = dt;
}
}
catch (Exception)
{
throw;
}
}
Take a look at you web.config if session is enabled. This post here might give more ideas.
https://stackoverflow.com/a/15711748/314373
In C#, on code behind page using web method,
[WebMethod(EnableSession = true)]
public static int checkActiveSession()
{
if (HttpContext.Current.Session["USERID"] == null)
{
return 0;
}
else
{
return 1;
}
}
And, in aspx page,
$.ajax({
type: "post",
url: "", // url here
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{ }',
crossDomain: true,
async: false,
success: function (data) {
returnValue = data.d;
if (returnValue == 1) {
}
else {
alert("Your session has expired");
window.location = "../Default.aspx";
}
},
error: function (request, status, error) {
returnValue = 0;
}
});