Deserialize JSON into dictionary in Web Api controller - javascript

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)
{
//code goes here
return null;
}
And always sendedData == null. Another words: I don't know how to deserialize JSON into (Dictionary<int, List<int>>.
Thank you for answer.

Try this
[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);
}

You can send the data like this:
{"sendedData":[{"key":"1","value":[1,3,5]},{"key":"2","value":[2,5,6]},{"key":"3","value":[5,6,8]}]}
Image of the function in the controller:
Dict

Try it:
Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<int, List<string>>>("{'1':[1,3,5],'2':[2,5,6],'3':[5,6,8]}");

Try using:
public ActionResult Parse(string text)
{
Dictionary<int, List<int>> dictionary = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<int, List<int>>>(text);
return Json(dictionary.ToString(), JsonRequestBehavior.AllowGet);
}
This works when the sent data doesn't have quotes around the indices:
{1:[1,3,5],2:[2,5,6],3:[5,6,8]}
Also make sure that you send an object in the Javascript:
data: {
text: JSON.stringify(sendedData)
},

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

You missed the [FromBody] annotation in the sendedData param. Try this:
[HttpPost]
[Consumes("application/json")]
[Produces("application/json")]
public object Dict([FromBody] Dictionary<int, List<int>> sendedData)
{
//code goes here
return null;
}

Related

json string on POST to MVC action method using AJAX is null

I am getting a hard time to find out why the string sent via AJAX request is null. Console.WriteLine(data) shows empty. Status is 200 OK. If I add some code to parse the string received, I get an error stating that JObject.Parse cannot be null. I don't know what am I missing. The javascript code is ok. The action method also seems ok, but my knowledge on Asp.Net Core and MVC is very scarce, so I am not sure. Can someone please point out what am I missing?
The javascript code:
let obj = {email: email_address.value};
let objStringified = JSON.stringify(obj);
$.ajax({
type: 'POST',
contentType: 'application/json; charset=UTF-8',
data: objStringified,
url: '#Url.Action("ReturnCheckAccountDuplication")',
dataType: 'text',
success: function(data) {
console.log(data);
},
error: function(error) {
console.log("Keep trying", error);
}
});
C# code:
[HttpPost]
public ActionResult ReturnCheckAccountDuplication([FromBody] string data)
{
Console.WriteLine(data);
JObject jObject = JObject.Parse(data);
string email = (string)jObject["email"];
bool emailExists = CheckAccountDuplication.Get(email);
string returnResult = emailExists.ToString();
return Content(returnResult);
}
The solution on the controller side is
public class AccountCheckModel
{
public string Email { get; set; }
}
[HttpPost]
public ActionResult ReturnCheckAccountDuplication([FromBody] AccountCheckModel data)
{
string result = CheckAccountDuplication.Get(data.Email).ToString();
return Content(result);
}
Thanks to all the members who commented on my problem, especially John Glenn who provided a solution. I had been trying for several days but without success. My knowledge of Asp.Net Core is very poor indeed. Thank you very much.
The easiest solution is to create a model representing the JSON data that your controller will receive. For example, create a class like so:
public class AccountCheckModel
{
public string email { get; set }
}
Then, use it as the parameter for your controller method:
public ActionResult ReturnCheckAccountDuplication([FromBody] AccountCheckModel data)
This is the preferred way to access the request body. To get the request body as a string, you have to jump through some serious hoops.
An alternative way to send your data via AJAX to your Controller:
var json = {
email: email_address.value
};
$.ajax({
type: 'POST',
data: {'json': JSON.stringify(json)},
url: '#Url.Action("ReturnCheckAccountDuplication")',
dataType: 'json',
success: function(data) {
console.log(data);
},
error: function(error) {
console.log("Keep trying", error);
}
});
And your Controller:
[HttpPost]
public ActionResult ReturnCheckAccountDuplication(string json)
{
Console.WriteLine(json);
JObject jObject = JObject.Parse(json);
string email = (string)jObject["email"];
bool emailExists = CheckAccountDuplication.Get(email);
string returnResult = emailExists.ToString();
return Content(returnResult);
}

How to get array list data using ajax call (pass array list data controller to ajax method)

My controller class like that.
#RequestMapping(value = {"/ajaxcallabd"}, method = RequestMethod.POST)
#ResponseBody// <== this annotation will bind Arr class and convert to json response.
String addAnotherAppointmenttt(HttpServletRequest request, HttpServletResponse response, #RequestBody String userJson, Model model, BindingResult errors) {
System.out.println("*******88888" + userJson);
List<stageViiChartData> chartData = stageViiChartDataServices.findBystageViiChaData(userJson);
return chartData.toString();
}
The above code create the List data. I want to pass above list data using ajax call.
My ajax method like that.
$.ajax({
type: "POST",
url: "/MobitelProgressTool/ajaxcallabd",
data: userJson,
contentType: "application/json; charset=utf-8",
// dataType: 'JSON',
datatype:'text',
success: function (mJSONArray) {
alert(mJSONArray);
},
failure: function (erroes) {
alert(erroes + ">>>>>");//handle it in a proper way
}
});
But above mJSONArray is string type. I want to get Json type. I don't know how I create it.
my chartData array like that.
[[stageViiChartDataModal: Updated_Scope = Ericsson, Dependency = WIP, On_Air_date = 4-Dec-15], [stageViiChartDataModal: Updated_Scope = Ericsson, Dependency = WIP, On_Air_date = 9-Dec-15]]
Just do..
success: function (mJSONArray) {
var d = JSON.parse(mJSONArray);
alert(d);
},
Change your Content-Type Content-Type: application/jsonthen you can pass json arral list data.
public class AppConfig extends WebMvcConfigurerAdapter {
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.ignoreAcceptHeader(true).defaultContentType(MediaType.TEXT_HTML);
configurer.ignoreAcceptHeader(true).defaultContentType(MediaType.APPLICATION_JSON);
}

getting null value in list when passing by ajax call to mvc controller

I am passing my list to an mvc controller but I am getting null value in the controller.But my list has values when show in alert on client side.
ajax call
$("#addTiles").click(function() {
userTiles = JSON.stringify({
'userTiles': userTiles
});
alert("Entered function.");
alert(userTiles[0].TileID);
var url = '#Url.Action("AddTiles")';
$.ajax({
type: "GET",
url: url,
data: userTiles,
success: function(d) {
if (d.indexOf('"IsSessionExpired":true') != -1) {
location.reload();
} else {
onAddTilesSuccessful(d);
}
},
error: function() {
errorInOperation();
},
contentType: "application/html; charset=utf-8",
dataType: 'html'
});
});
function onAddTilesSuccessful(e) {
$("#tilesSubmissionMsg").append(e);
}
function errorInOperation(d) {
$("#tilesSubmissionMsg").append("Something went wrong");
}
mvc controller
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
List Model
public class UserTilesVM
{
public int TileID { get; set; }
public int TopPosition { get; set; }
public int LeftPosition { get; set; }
}
List in javascript
"{"userTiles":[{"TileID":"3","TopPosition":0,"LeftPosition":0}]}"
I have also tried by sending my list with stringfy but that also doesn't work.
Use : [HttpGet] on the method AddTiles as you have used type: "GET" on the Ajax hit.
[HttpGet]
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
If Still doesn't works then try type: "POST" on Ajax hit and on method use [HttpPost]
[HttpPost]
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
You have contentType and dataType twice in your AJAX setup, with different values, which will break the AJAX call.
Keep in mind contentType is to tell the server what type of data to expect and dataType is to determine what type of data is returned, from the documentation.
Edit: I see you have edited your code!
In this case, since you are using JSON.Stringify to modify the data you are sending, you would use contentType: "application/json; charset=utf-8", as your contentType, since you are sending JSON data to the backend.
when we are trying to pass object data using ajax, we have to store data in variable and pass data directly using "data :'variable'" in AJAX to Controller Method
$("#addTiles").click(function() {
var userTiles = ({
'userTiles': userTiles
});
alert("Entered function.");
alert(userTiles[0].TileID);
var url = '#Url.Action("AddTiles")';
$.ajax({
type: "POST",
url: url,
data: userTiles,
success: function(d) {
if (d.indexOf('"IsSessionExpired":true') != -1) {
location.reload();
} else {
onAddTilesSuccessful(d);
}
},
error: function() {
errorInOperation();
},
contentType: "application/html; charset=utf-8",
dataType: 'html'
});
});
function onAddTilesSuccessful(e) {
$("#tilesSubmissionMsg").append(e);
}
function errorInOperation(d) {
$("#tilesSubmissionMsg").append("Something went wrong");
}
//Use [HttpPost] keyword for getting value which was passed by AJAX.
[HttpPost]
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
I think your list definition is not ok:
"{"userTiles":[{"TileID":"3","TopPosition":0,"LeftPosition":0}]}"
should be:
"{"userTiles":[{"TileID":"3","TopPosition":"0","LeftPosition":"0"}]}"
i have using this sequence that work fine
you have check the
contentType: "application/json",
dataType: "json",
sequence in ajax method

Why does this call to my controller not work?

I have the following JavaScript code on my view in MVC4 project:
jQuery.ajax({
url: "/Object/GetMyObjects/",
data: {
__RequestVerificationToken: jQuery("input[name='__RequestVerificationToken']").val(),
},
type: "POST",
traditional: true
}).success(function (data) {
sfds = JSON.parse(data);
});
and the following method in ObjectController:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult GetMyObjects()
{
var sfds= _db.SFDS.ToList();
return View(sfds);
}
Why does the controller not get called when the JavaScript is run? Even when I remove the ValidateAntiForgereToken it does not work. In my console I see data returned is null.
I'm having a hard time getting some JSON on my view today.
You aren't returning JSon. You are returning (or attempting to return) a view. You need something like this, in your controller:
return Json(sfds, JsonRequestBehavior.AllowGet);
And, add this to your .ajax() properties:
dataType: "json",

Call ASP.NET C# Controller Method from Javascript

I have a var toto in a javascript file. And I want to call a C# Controller Method who return a string and of course assign the resulted string to toto.
I tried some ways to achieve this but nothing seems to work.
Somebody can explain me the simpliest way to achieve that ? It's a Windows Azure project.
Many Thanks !
You could use AJAX. For example with jQuery you could use the $.getJSON method to send an AJAX request top a controller action that returns a JSON encoded result and inside the success callback use the results:
$.getJSON('/home/someaction', function(result) {
var toto = result.SomeValue;
alert(toto);
});
and the controller action:
public ActionResult SomeAction()
{
return Json(new { SomeValue = "foo bar" }, JsonRequestBehavior.AllowGet);
}
You have to use JSON:
Controler
public class PersonController : Controller
{
[HttpPost]
public JsonResult Create(Person person)
{
return Json(person); //dummy example, just serialize back the received Person object
}
}
Javascript
$.ajax({
type: "POST",
url: "/person/create",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: jsonData,
success: function (result){
console.log(result); //log to the console to see whether it worked
},
error: function (error){
alert("There was an error posting the data to the server: " + error.responseText);
}
});
Read more: http://blog.js-development.com/2011/08/posting-json-data-to-aspnet-mvc-3-web.html#ixzz1wKwNnT34

Categories

Resources