JSON passed to controller has no value - json

I am unable to get my JSON to my controller, and I can't figure out why the value I get in javascript isn't being passed to the controller. Here is my ajax post in my javascript:
this.save = function () {
var data = ko.toJSON(this.Routines);
$.ajax({
type: 'POST',
url: "CreateJson",
data: data,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
if (!result.success)
alert("test")
else { }
}
})
}
now data contains
[{"routine_name":"new routine","duration":"20","rest":"10","rounds":1}]
which is what I want, but the controller shows nothing. Here is my controller
[HttpPost]
public JsonResult CreateJson(t_routine routine, string data)
{
var message = "success";
return Json(message);
}
As I understand it, MVC 3+ automatically receives JSON without any need for parameters like my string data, I just threw it in there to try and figure out if I'm getting anything at all. data is null and routine shows 0's and null for values. What am I missing?

If t_routine represents the server side type for
[{"routine_name":"new routine","duration":"20","rest":"10","rounds":1}]
Then it might be enough to call JSON.stringify on the ko.toJSON result like this
this.save = function () {
var data = JSON.stringify(ko.toJSON(this.Routines));
$.ajax({
type: 'POST',
url: "CreateJson",
data: data,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
if (!result.success)
alert("test")
else { }
}
})
}
the data parameter on your controller action is not needed then and you most likely need to change the t_routine parameter to t_routine[]

Related

IformFile in the action controller takes the value as null, value is pass to the action controller using ajax request

I am trying to get the value passed from the ajax request into one of the method in the controller but IFormFile files is null every time.
Here is my ajax request :
uploadFile: function (field, value)
{
var me = this;
var view = me.getView();
var fileuploadControl = me.lookupReference('ImportFile');
var file = fileuploadControl.fileInputEl.el.dom.files[0];
var param = new FormData();
param.append('files', file);
var ajax = Ext.Ajax.request(
{
url: './../XYController/ImportCSVFile',
data: param,
method: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: { 'accept': '*/*' },
processData: true,
success: function (response, options) {
var result = JSON.parse(response.responseText);
if (mask) {
mask.destroy();
}
Ext.Msg.alert("File Upload Successful");
}
});
},
And this is my Action Controller :
[HttpPost]
[Route("XYController/ImportCSVFile")]
public IActionResult ImportCSVFile(IFormFile files)
{
if(files!=null)
{
//do something
}
}
For file upload , The contenttype needs to be set to false along with the processData option. Otherwise jQuery will not see this as a file upload :
processData: false,
contentType: false,
See code samples from here , that should be same no matter use ExtJS or other Jquery wrapper library .

how to pass serialize data and stringified data together in ajax

I have a ajax function where i am passing two objects:
1) serialize form data object
2) complex object
Ajax function:
var temp = sessionStorage.getItem('book');
var viewName = $.parseJSON(temp);
var ViewModel = $("#OffsetBookForm").serialize();
$.ajax({
contentType: "application/json; charset=utf-8",
type: "Post",
url: "#Url.Content("~/Estimate/CreateOrder")",
data: JSON.stringify({ 'OffsetCommonObj': ViewModel, 'obj': viewName }),
dataType: 'json',
success: function (data) {
}
});
And My ActionMethod:
public ActionResult CreateOrder(EstimationOffsetViewModel OffsetCommonObj,
OffsetCostCalculation obj)
{
// do something here..
}
My problem is, the first object in action method i.e-"OffsetCommonObj" is getting null. What am I doing wrong in the code? Please Help..Thanks.

Why can I not extract the data from this basic JSON Example

This is my Java script
function displayCustomerData( p_customername )
{
$.ajax({
url: 'myservlet',
type: 'GET',
data: { requesttype : "getcustomerdata" ,
customername : p_customername } ,
contentType: 'application/json; charset=utf-8',
success: function ( data )
{
$("#usernametxt").val( data.customer);
},
error: function () {
alert("Error loading customer data");
}
});
on the server side I generate the JSON using the Gson library
Gson gson = new Gson();
return gson.toJson( customerData );
customerData is a simple POJO with two String fields
I have a breakpoint at the Success response from the server
This is what the "data" variable contains in my debugger when I try to get the data from it
data "{"customer":"cuatomer A","userName":"user A"}"
but on my browser console when I do "data.customer" it tells me that customer is undefined ?
This indicates that there is something wrong with the JSON data but I don't see anything wrong and I can't stare at it any longer... anyone see anything?
I have tried it on Chrome and Firefox incase it was a browser issue, same problem on both.
you can parse the Data like using JSON.parse(data) and try for data.customer u can get .the result ....
function displayCustomerData( p_customername )
{
$.ajax({
url: 'myservlet',
type: 'GET',
data: { requesttype : "getcustomerdata" ,
customername : p_customername } ,
contentType: 'application/json; charset=utf-8',
success: function ( data )
{
var data1 = JSON.parse(data);
$("#usernametxt").val( data1.customer);
},
error: function () {
alert("Error loading customer data");
}
});

AJAX/JSON MVC method not being called

The MVC controller method is not being called with the following code and the issue isn't clear. $("#screeners").val() returns a list of strings:
<script>
$(document).ready(function () {
$("#submitScreeners").click(function () {
var selected = $("#screeners").val();
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Applicant/PassScreeners',
data: "selected=" + JSON.stringify(selected),
success: function () {
$('#result').html('"PassScreeners()" successfully called.');
},
failure: function (response) {
$('#result').html(response);
}
});
});
});
</script>
Method in controller:
public void PassScreeners(List<string> selected)
{
Session["SelectedApplicants"] = selected.Select(e => Int32.Parse(e.ToString())).ToList();
}
If I understand you correctly, the "selected" parameter is being passed in as a null value. I believe this is because you are using an incorrect data format. You tell the server to expect JSON formatted data, but then pass it something more akin to a form value with '='.
Try removing the "selected=" bit from your data line and just pass the stringified list.
If that doesn't work, check the trace and post it. If the string you are posting is just comma separated or something it needs to be an array in order for the POST to work correctly.
Apologies if I've misunderstood.

ajax post multiple parameters does not pass properly to asp.net mvc action

I am not able to pass 2 parameters to the action method as json. I have the following ASP.net MVC3 action.
[HttpPost]
public JsonResult Create( PatientContactEpisodes patientcontactepisode, IList<PatientContactEpisodeProcedures> patientcontactepisodeprocedures)
And my ajax post looks like this.
$("#SaveButton")
.button()
.click(function () {
var episode = getpatientcontactepisode();
$.ajax({
type: 'POST',
traditional: true,
url: "/User/PatientContactEpisodes/Create",
contentType: 'application/json, charset=utf-8',
data: {patientcontactepisode: JSON.stringify(episode), patientcontactepisodeprocedures: JSON.stringify(createArray)},
//data: JSON.stringify(episode),
dataType: "json",
success: function (results) {
alert("success");
}
});
});
ISSUE
The issue is that the value does not seem to be passed when I send both parameters to the action. Both are null/empty. Whereas, when i send a single parameter
//data: JSON.stringify(episode), or //data: JSON.stringify(createarray),
The above works fine.
Try:
data: {JSON.stringify({patientcontactepisode: episode, patientcontactepisodeprocedures:createArray})},
This should do the stuff for you.