How to POST some properties using an AJAX array? - ajax

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?

Related

I can't send data to a list of objects with ajax

net core 6.0 code class :
public class plansdto{
public short status { get; set; }
public List<PlanItemDto> items { get; set; }
}
public class PlanItemDto{
public short currency
}
Ajax code :
<script>
$("#button").click(function() {
let plandto= {};
plandto.status = $("input[name='status']").val();
plandto.items = $("input[currency='currency']".val();
});
$.ajax({
traditional: true,
type: "post",
url: "/CommissionPlan/CreateAccountsCommission",
data: plandto,
success: function(func) {
let result = JQuery.parseJSON(func);
alert("ok");
}
});
</script>
not working!
status data sent but items data isnot sent.
plase help me. Ajax Object inside List send data

Adding via ajax one to one related data .net Core

I have 2 tables, one is a one to one or one to zero relationship:
public class ComponentText
{
[Key]
public int ComponentTextId { get; set; }
public string ComponentContent { get; set; }
public ComponentTextSection ComponentTextSection { get; set; }
}
public class ComponentTextSection
{
[Key]
public int ComponentTextId { get; set; }
public string SectionTitle { get; set; }
public ComponentText ComponentText { get; set; }
}
I can add row fine using usual .net core posting using a form, here is code which does this:
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
var newComponentText = new ComponentText();
if (await TryUpdateModelAsync<ComponentText>(
newComponentText,
"ComponentText",
i => i.ComponentTextSection, i => i.ComponentContent))
{
_context.ComponentText.Add(newComponentText);
await _context.SaveChangesAsync();
}
return RedirectToPage("./Index");
}
I need to update though via ajax, but I am having issues updating the SectionTitle using this current way. It adds the data to the ComponentText table fine but not the ComponentTextSection table. Here is my ajax code:
function saveWindow() {
var ComponentText = { "ComponentText.ComponentTextSection.SectionTitle": $("#ComponentText_ComponentTextSection_SectionTitle").val(),
"ComponentTextId": $("#ComponentText_ComponentTextId").val(),
"ComponentContent": $("#ComponentText_ComponentContent").val()};
$.ajax({
type: 'PUT',
contentType: 'application/json; charset=utf-8',
headers: {
'RequestVerificationToken': '#AntiForgery.GetAndStoreTokens(HttpContext).RequestToken'
},
data: JSON.stringify(ComponentText),
url: '#Url.Page("Edit", "demo4")',
success: function (result) {
closeWindow();
}
});
}
It must be to do with ComponentText.ComponentTextSection.SectionTitle but I have been trying lots of things to get this to work but failing. Does anyone know how to pass a one to one related data via ajax?
Thanks
For the one-to-one model, if you want to use ajax to transfer the complex nested model to the page, you need to create the same as the ComponentText model structure in saveWindow function of ComponentText variable.
<script>
function saveWindow() {
var ComponentText = {
"ComponentTextSection":
{
"SectionTitle": $("#ComponentText_ComponentTextSection_SectionTitle").val(),
},
"ComponentTextId": 1,
"ComponentContent": $("#ComponentText_ComponentContent").val()
};
$.ajax({
type: 'PUT',
contentType: 'application/json; charset=utf-8',
headers: {
'RequestVerificationToken':
'#AntiForgery.GetAndStoreTokens(HttpContext).RequestToken'
},
data: JSON.stringify(ComponentText),
url: '#Url.Page("Edit", "demo4")',
success: function (result) {
closeWindow();
}
});
}
</script>
Here is the test result:

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)

Empty data send by json

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 :)

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