Empty data send by json - ajax

For unknown reason for me data received by my function in controller is always null.
My data is translated into json properly. Data is send but not received (sending ends with success).
Here You can see my Ajax function
$.ajax({
url: "/Devices/Read",
contentType: "text",
type: "POST",
datatype: "json",
data: ko.toJSON(self),
error: function (xmlHttpRequest, errorText, thrownError) {
console.log("error")
},
success: function (data) {
if (data != null) {
console.log("success");
}
}
});
here my function in controller:
[HttpPost]
public ActionResult Read(string data)
{
return Json(new Object());
}
I tried:
changing parameter type to: Object, String
changing contentType to : text, application/json; charset=utf-8
Still no efects. Can anyone suggest me where should I search for mistake?
UPDATE:
After changing method declaration to:
public ActionResult Read(object[] data, string DeviceUser, string DeviceId, string number)
Last three strings are OK but first object consist of proper number of elements but they are null.
in JS they are alements in array of classes
structure of my JS objects:
var Eq = function (name, price) {
var self = this;
self.DeviceSerialNumber = ko.observable();
self.Batch = ko.observable();
};
var ViewModel = function () {
var self = this;
self.data = ko.observableArray([]);
self.DeviceUser = ko.observable();
self.DeviceId = ko.observable();
self.number = ko.observable(1);
};

In your controller action, why do you:
return RedirectToAction("Index");
I think you may want to:
return Json(data);

If you are writing an HTTP Post method, then the redirect to action does not really make sense, because you are posting data, not requesting a page.
You could do something like this:
[HttpPost]
public ActionResult Read(string Data)
{
return Json(Data);
}

OK problem was in setting proper parameter type in method.
TO solve my problem I need to modify method declaration to:
public ActionResult Read(ViewModel m)
and add ViewModel like this:
public class ViewModel
{
public List<InnerClass> data { get; set; }
public string DeviceUser {get;set;}
public string DeviceId {get;set;}
public int number {get;set;}
}
public class InnerClass
{
public string DeviceSerialNumber { get; set; }
public string Batch { get; set; }
}
now all data is received.
Thanks You all for help and suggestions. I will give you all +1 :)

Related

How to pass dictionary item from client side (Ajax) to server side (MVC API)

I want to pass multiple key and value pair of dictionary type from client side using post method to server side which is MVC Web API HTTP get method.
function FileSenderAPI(){
var DictionaryData = new Object;
DictionaryData = document.getElementById("hidFilePath").value;
var Url = '<%=System.Configuration.ConfigurationManager.AppSettings["FileSenderAPI"].To String() %>';
$.ajax({
url: Url,
method: 'Get',
data Type: "json",
data: {
ModelsPath:JSON.stringify(DictionaryData),
Exchange: exchange,
Exchange_key: key,
},
success: function (data, textStatus, xhr) {
alert(data);
},
}
public HttpResponseMessage ConvertModel(Dictionary<string, string> ModelsPath,string Exchange,string Exchange_key)
{
} // its my API method.``
Here is a solution. You can try it. Hope to help, my friend :))
1) Create a model
public class DictionaryModel
{
public Dictionary<string, string> dict { get; set; }
public string Exchange { get; set; }
public string Exchange_Key { get; set; }
}
2) Action
[HttpPost]
public JsonResult Example(DictionaryModel model)
{
// Your Logic
return Json("Success");
}
3) In View
$('#btClick').on('click', function () {
var dict = {};
dict["id"] = "200";
dict["Name"] = "Chris";
dict["DynamicItem1"] = "Item 1";
var theObject = {};
theObject.dict = dict;
theObject.Exchange = "Abc";
theObject.Exchange_Key = "123";
let url = '#Url.Action("Example","Home")';
$.post( url, theObject, function (data, textStatus, XMLHttpRequest) {
console.log("success");
}, "json");
});

Problems with Post Ajax in Asp.net core MVC

I can not send a Model that I am manually creating to my controller. When I send the request, it's coming up with empty properties. There is something wrong that is hindering the conversion. Does anyone know how to help me?
var operadoraChamadas = {
Id: 0,
Descricao: 'rssrrssr',
PadraoSistema: true
};
var requestData = { operadoraChamadasViewModel: operadoraChamadas}
$.ajax({
url: "/pessoa-gerenciar/changeFormaContato",
type: "POST",
data: JSON.stringify(requestData),
contentType: "application/json",
dataType: "json",
success: function (result) {
alert('ok');
},
error: function () {
alert("Oops! Algo deu errado.");
console.log(requestData);
}
});
[HttpPost]
[Route("pessoa-gerenciar/changeFormaContato")]
public IActionResult changeFormaContato(OperadoraChamadaViewModel operadoraChamadaViewModel)
{
//ViewBag.indice_new = indice;
//return PartialView("~/Views/Pessoa/PessoaContato/_PessoaContatoAdd.cshtml", _pessoaContatoAppService.CreateNew(pessoaNatureza, formaContatoId));
return null;
}
ViewModel:
public class OperadoraChamadaViewModel
{
[Key]
[DisplayName("ID")]
public int Id { get; set; }
[Required(ErrorMessage = "A Descrição é obrigatória")]
[MaxLength(50)]
[DisplayName("Descricao")]
public string Descricao { get; set; }
[DisplayName("Padrão do Sistema")]
public bool PadraoSistema { get; set; }
}
ASP.NET Core requires to add [FromBody] attribute to parameter to parse application/json content
[HttpPost]
[Route("pessoa-gerenciar/changeFormaContato")]
public IActionResult changeFormaContato([FromBody] OperadoraChamadaViewModel operadoraChamadaViewModel)

How to pass parameters to GET WebApi endpoint via AJAX call?

I have a GET WebApi endpoint that's part of my MVC application that I want to use to process some data I send to it, and am to accomplish the sending of this data via a jQuery AJAX call.
However, I'm having some trouble passing in the parameters I want, via the AJAX call. Currently I'm compiling all the parameters I need into one object, using JSON.stringify() to convert the parameters into a string, and sending along that as data.
Is there something else I'm missing here? I'm able to pass these parameters along just fine if I'm doing a POST, but I'd like to avoid that since my endpoint is not responsible for inserting or updating any data.
Below is the code I'm using for both WebApi endpoint and AJAX call.
WebApi endpoint:
Method:
[HttpGet]
[Route("api/services/getservices")]
public IHttpActionResult GetServices(ServiceViewModel vm)
{
return Ok(Request);
}
Classes:
public class ServiceViewModel
{
public ServiceModel service { get; set; }
}
public class ServiceModel
{
public string thing1 { get; set; }
public string thing2 { get; set; }
public string thing3 { get; set; }
public string thing4 { get; set; }
}
AJAX:
var thing1 = $("#thing1").find(":selected").attr("program-id");
var thing2 = $("#thing2").val();
var thing3 = $("#thing3").val();
var thing4 = $("#thing4").val();
var obj = {
thing1: thing1,
thing2: thing2,
thing3: thing3,
thing4: thing4
};
obj = { "service": obj };
$.ajax({
contentType: "application/json",
url: "/api/services/getservices",
type: "GET",
data: JSON.stringify(obj),
cache: false,
success: function (data) {
console.log(data);
console.log("got here");
serviceTable(data);
},
error: function () {
servicEngineService.getProgramServices(programId, generateServiceTable, getProgramServicesFailure);
}
});
You should use:
data: {
thing1: thing1,
thing2: thing2,
thing3: thing3,
thing4: thing4
};
They will be passed in the query string, so take care, it shouldn't be too long.
As Nkosi said, GET requests don't have a body. If it gets too long for the query string you should use a POST, even if your back-end won't modify data.

How to POST some properties using an AJAX array?

I want to POST my array data through AJAX posting method.
For getting those values in an array, I have used a ViewModel.
My controller code is as::
[HttpPost]
public ActionResult SavePlaylist(List<ItemEditViewModel> data, long playlistid, List<long> deleted, string Title)
{
for (int i = 0; i < data.Count; i++)
{
var pc = new PlaylistContent();
}
return Playlist(playlistid);
}
I have used my AJAX posting as ::
$.ajax({
type: 'POST',
data: { data: data , playlistid: parseInt(playlistid) },
traditional: true,
url: 'SavePlaylist',
success: function (data) {
search(playlistid,"Playlist");
alert("Playlist saved successfully!!");
}
})
Here my data POSTed in the form as::
data:[object object]
data:[object object]
data:[object object]
Playlistid:5
Its not matching the ViewModel made as:
public class ItemEditViewModel
{
public long ID { get; set; }
public long MetaID { get; set; }
}
How can I get all the values POSTed using this kind of array?

serialize List<SelectListItem> from View to Controller in MVC 3

I'm having issues passing my list object to my controller - using an ajax post.
in the view I have this:
try {
var id = schedule.value;
var data2 = #Html.Raw(Json.Encode(Model.SavedScheduleList));
var url = '#Url.Action("SetActiveSchedule", "Frame")';
$.post(url, { savedScheduleList: data2, signScheduleDataId: id }, function (data) {
});
}
catch (err)
{
alert(err);
}
My Controller looks like this:
[HttpPost]
public ActionResult SetActiveSchedule(List<SelectListItem> savedScheduleList, int signScheduleDataId)
{
try
{
return Json(null);
}
catch (Exception ex)
{
throw;
}
}
So when my Action is executed, my savedScheduleList contains a list object with 7 objects (which is the correct number of items I'm sending through. However each item seems to be "blank". ie, of the SelectListItem class, these are the property values for each item: Selected = false, Text = null, Value = null.
The Model class (which has been strongly typed to this view) is:
public class ScheduleModel
{
private SignSchedule activeSignSchedule = new SignSchedule();
private List<SelectListItem> savedSignScheduleList = new List<SelectListItem>();
public int SignDataId { get; set; }
public ScheduleFrameList ListFrames { get; set; }
public DateTime Start { get; set; }
public LogMessage LogMessage { get; set; }
public bool CommsLogVisible { get; set; }
public SignSchedule SignScheduleToMakeActive { get; set; }
public int ActiveSignScheduleId { get; set; }
//public List<SignSchedule> SavedSignScheduleList { get { return savedSignScheduleList; } }
public List<SelectListItem> SavedScheduleList { get { return savedSignScheduleList; } }
}
Examining data2 before the post, shows the correct data in Json format and examining the Request property within the Action I can see the correct values in the Form.AllKeys property as well as the Params property but it doesn't seem to correctly resolve it back to my parameter object of the Controller Action.
Is it possible what I'm trying to do?
Thanks
EDIT
Here's a string representation of data2 variable:
var data2 = [{"Selected":false,"Text":"9","Value":"2589"},false,"Text":"afsdfs","Value":"2585"},false,"Text":"sdfas","Value":"2588"}....]
I'm just showing 3 items here but there is in fact 7 as expected.
The easiest way to send complex objects and lists is to use a JSON request, like this:
var id = schedule.value;
var data2 = #Html.Raw(Json.Encode(Model.SavedScheduleList));
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ savedScheduleList: data2, signScheduleDataId: id }),
traditional: true,
success: function(result) {
// TODO: do something with the results
}
});
Note that the JSON.stringify function is natively built into modern browsers. But if you need to support legacy browsers you could include the json2.js script into your page.

Resources