Deserialize JSON in Dictionary in Web Api: always empty string - c#

I have such JSON string: {"1":[1,3,5],"2":[2,5,6],"3":[5,6,8]}
I want to send it to the Web Api Controller without changing using ajax request:
$.ajax({
type: "POST",
url: "Api/Serialize/Dict",
data: JSON.stringify(sendedData),
dataType: "json"
});
In Web Api I have such method:
[HttpPost]
public object Dict(Dictionary<int, List<int>> sendedData)
{
var d1 = Request.Content.ReadAsStreamAsync().Result;
var rawJson = new StreamReader(d1).ReadToEnd();
sendedData=Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<int, List<string>>>(rawJson);
return null;
}
But rawJson always is empty string. I don't understand why?
But d1.Length is the same as in JSON string. I don't know how to get JSON string from d1...
Thank you!

use content type parameter instead of dataType when performing ajax call:
$.ajax({
type: "POST",
url: "Api/Serialize/Dict",
contentType: "application/json; charset=utf-8", //!
data: JSON.stringify(sendedData)
});

Related

AJAX post string array to webapi 2

Here is my ajax call:
var myIds = ["A","B","C"]
$.ajax({
type: "POST",
url: /DoStuffAndThings?year=2018&name=test,
data: {myIds: myIds},
traditional: false
});
Here is my controller action:
[HttpPost]
public void DoStuffAndThings(int year, string name, [FromBody] List<string> myIds) {
// do stuff
}
year and name come through without issue but myIds is always empty.
Ive tried
data: {myIds: myIds} and data: myIds and data: {"": myIds} and I tried using Ienumerable<string> and List<string> and string[]
and I've tried traditional: true and false
The model binder is unable to parse the send data as it does not know the format
Use JSON.stringify along with the corresponding parameters
var myIds = ["A","B","C"];
$.ajax({
type: "POST",
url: "/DoStuffAndThings?year=2018&name=test",
contentType: "application/json",
dataType: "json",
data:JSON.stringify(myIds),
traditional: false
});
The model binder should then be able to recognize the string collection in the body of the request.
When sending data to a web server, the data has to be a string.
Convert a JavaScript object into a string with JSON.stringify().
Before data, use JSON.stringify(myIds).
var myIds = ["A","B","C"]
$.ajax({
type: "POST",
contentType: "application/json",
dataType: 'json',
url: /DoStuffAndThings?year=2018&name=test,
data: JSON.stringify(myIds),
traditional: false
});

I'm getting a 404 when issuing an ajax call

Here is my ajax call
$.ajax({
async: false,
url: "/api/clients/UpdateResourceContactProductsByResourceContactId/" + id,
type: 'POST',
data: { strIds: strIds },
success: function (data) {
}
});
where id is the integer and strIds is a string contantenation of integers, they look like 123_254_741_6650 ...
And this the server side code ...
[HttpPost]
public IHttpActionResult UpdateResourceContactProductsByResourceContactId
(int id, string strIds)
{
//...
}
When I hit the update button, I'm getting the following error:
{"Message":"No HTTP resource was found that matches the request URI
'http://localhost/api/clients/UpdateResourceContactProductsByResourceContactId/22757'.",
"MessageDetail":"No action was found on the controller 'Clients' that matches the request."}
Am I missing something?
Try this...
$.ajax({
async: false,
url: "/api/clients/UpdateResourceContactProductsByResourceContactId",
type: 'POST',
data: { id: id, strIds: strIds },
success: function (data) {
}
});
I think you're passing the data wrong. You are passing a object. Either change you method to accept a JObject and use dynamic to pull the strIds out, pass the string by itself, or use it as a URL parameter.
//example using JObject below
[HttpPost]
public IHttpActionResult UpdateResourceContactProductsByResourceContactId(int id, JObject data)//JObject requires Json.NET
{
dynamic json = data;
string ids = json.strIds
}
If you are going to POST an object you need to call JSON.stringify on it too in the javascript.
var data = JSON.stringify({ strIds: strIds });
$.ajax({
async: false,
url: "/api/clients/UpdateResourceContactProductsByResourceContactId/" + id,
type: 'POST',
data: data,
success: function (data) {
}
});

JavaScript - extracting data from a JSON object created with Json.Net

I have a server-side method used to return the data to the user. The data is stored in a SQL Server database and is mapped using EF 6. Once extracted from the database using an id value, the object is subsequently serialized using the Json.NET framework. The object is used "as is", without filtering out the references to other tables. Because of that, I've had to use the "PreserveReferencesHandling" option.
On the client-side, AJAX is used to call the method. I'm having trouble extracting the data from the object (client-side) which does get serialized and is delivered to the browser as expected.
Server-side method:
[WebMethod]
public static string ContactData(long id)
{
IService<Contact> contactService = new ContactService();
Contact contactEdit = contactService.GetById(id);
string str = JsonConvert.SerializeObject(contactEdit, new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects
});
return str;
}
Client-side function (the important part):
$.ajax({
type: "POST",
url: "Contacts.aspx/ContactData",
data: JSON.stringify({ id: contactId }), // id by which I am receiving the object
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (contact) {
$("#tbFirstName").val(contact.d[0].Contact.first_name); // I've tried various combinations to no avail
},
});
This is how the JSON object (testing purposes data) looks like in Visual Studio's JSON Visualizer:
And this is what the browser (FF 32, it that matters) receives:
Firebug
I will post more info if needed.
First parse the json before you process it. and loop through it using jquery each function.
$.ajax({
type: "POST",
url: "Contacts.aspx/ContactData",
data: JSON.stringify({ id: contactId }), // id by which I am receiving the object
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (contact)
{
var contact=jQuery.parseJSON(contact);
$.each(contact, function(i, item) {
alert(i + " ==> "+ item.first_name);
});
}
});

Ajax JQuery Passing Data to POST method

I am a newbie at javascript and jquery and I would like some help if possible. I searched and tried to make it work, but I think I am missing something simple.
I have the following method in my cs file (CeduleGlobale.aspx.cs)
[WebMethod]
public static void SetSession(string data)
{
HttpContext.Current.Session["salesorderno"] = data;
}
I also have a some javascript in my ascx file
<script type="text/javascript">
function SetSession() {
var request;
var values = 'fred';
request = $.ajax({
type: "POST",
url: "CeduleGlobale.aspx/SetSession",
data: values,
contentType: "application/json; charset=utf-8",
dataType: "json"
});
request.done(function () {
alert("Finally it worked!");
});
request.fail(function () {
alert("Sadly it didn't worked!");
});
}
</script>
The function in the script is called by
<dx:ASPxCheckBox ID="cbxHold" runat="server" AutoPostBack="true" Text="OnHold" ClientSideEvents-CheckedChanged="SetSession">
</dx:ASPxCheckBox>
And the result i keep getting is "Sadly, it didn't work!".
I know the problem is not with anything relative to the path of the url, because it worked when i passed NULL as data and had the method with no parameters.
The parameters and data is what i tripping me I believe.
You should pass serialized JSON into the method:
var values = JSON.stringify({data:'fred'});
request = $.ajax({
type: "POST",
url: "CeduleGlobale.aspx/SetSession",
data: values,
contentType: "application/json; charset=utf-8",
dataType: "json"
});
You are specifying that you are sending JSON, but you don't serialize the value to JSON, so try changing the request to this:
request = $.ajax({
type: "POST",
url: "CeduleGlobale.aspx/SetSession",
data: JSON.stringify({data: values}), // 'stringify' the values to JSON
contentType: "application/json; charset=utf-8",
dataType: "json"
});
'fred' is not json nor object
use object notation :
{"myattr":"fred"} //you can also do {myattr:"fred"}
and then use JSON.stringify which transform it into STRING representation of json object.
The data sent through post should be sent in a {key:value} format
values={name:'fred'}
The data should be passed into [key:value] pair.

Send JSON to webmethod?

How can i send a JSON object to a webmethod using jQuery?
Please refer to this article by Dave Ward. It is a complete tutorial on doing this stuff. Also you will find there other great jquery/ASP.net stuff.
EDIT:- Dave is calling method without any arguments, you can replace empty data property with actual data you want to send:
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{'name':'tiger1','hobbies':['reading','music']}",//PUT DATA HERE
contentType: "application/json; charset=utf-8",
dataType: "json",
WebMethods expect a string containing JSON that will be parsed on the server-side, I use the JSON.stringify function to convert a parameters object to string, and send the data, I have a function like this:
jQuery.executePageMethod = function(location, methodName, methodArguments,
onSuccess, onFail) {
this.ajax({
type: "POST",
url: location + "/" + methodName,
data: JSON.stringify(methodArguments), // convert the arguments to string
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, status) {
var jsonData = JSON.parse(data.d);
onSuccess(jsonData, status);
},
fail: onFail
});
};
I recommend you to include the json2.js parser in your pages, to have the JSON.stringify function cross-browser available.
Another library you can use is the jquery-json library. Once included:
var json = $.toJSON(your_object);
The most convenient solutions I've seen simplify this by using the open-source JSON2.js library to parse and 'stringify' complex object data.
These two excellent articles go into detail:
Using complex types to make calling services less… complex by Dave Ward.
JavaScript Arrays via JQuery Ajax to an Asp.Net WebMethod by Chris Brandsma.
The second article might be especially relevant for you, though it calls a web service method with the following signature ...
public void SendValues(List<string> list)
... it demonstrates how to use the JSON2.js library to render a List<string> in javascript (using jQuery, this example is taken directly from the second article):
var list = ["a", "b", "c", "d"];
var jsonText = JSON.stringify({ list: list });
// The 'list' is posted like this
$.ajax({
type: "POST",
url: "WebService1.asmx/SendValues",
data: jsonText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() { alert("it worked"); },
failure: function() { alert("Uh oh"); }
});
Just use your webmethod URL in lieu of the web service's.
You'd need to post it using Ajax and accept the incoming string on the webmethod. Then you'd need to use the JavaScript deserializer to convert it into an object on the server side.
JSON.stringify does help, but:
it's not cross-browser
take a look here:
http://www.sitepoint.com/blogs/2009/08/19/javascript-json-serialization/#
For browser in-built functions - every browser will have its problems. If You use the above serialization You will need to:
remove newlines with regexp in strings
take care about " in strings
Sample code is here:
var dataString = JSON.stringify({
contractName: contractName,
contractNumber: contractNumber
});
$.ajax({
type: "POST",
url: "CreateQuote.aspx/GetCallHistory",
data: dataString,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result.CallHistoryDescription);
OpenLightBox('divDelete');
}
});
[System.Web.Services.WebMethod]
public static object GetCallHistory(string contractName, string contractNumber)
{
return new
{
CallHistoryDescription = "Nalan"
};
}

Categories

Resources