How can I properly save a FullCalendar event to a database? - javascript

I'm having some struggle with FullCalendar as I'm not good at JavaScript.
I'm using a Drag-n-Drop Event calendar (https://fullcalendar.io/docs/external-dragging) and I'm having some problem to save an event when I drag it to the calendar.
The code I use to save it is the following:
eventReceive: function (event) {
console.log(event.start);
console.log(event.title);
console.log(event.allDay);
console.log(event.eventID);
var data = {
Id: event.eventID,
Titulo: event.title,
Inicio: event.start.format('DD/MM/YYYY HH:mm'),
Fim: event.end != null ? event.end.format('DD/MM/YYYY HH:mm') : null,
DiaInteiro: event.allDay,
Cor: event.eventColor
};
SaveEvent(data);
},
});
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '/Escala/SaveEvent',
data: data,
success: function (data) {
if (data.status) {
calendar.render();
}
},
error: function () {
alert('Failed');
}
})
But as you can see, when I drag an event into the calendar, I have these problems:
Errors
I have an Event class with these attributes
public class Evento
{
public Guid Id { get; set; }
public string Titulo { get; set; }
public Nullable<System.DateTime> Inicio { get; set; }
public Nullable<System.DateTime> Termino { get; set; }
public bool DiaInteiro { get; set; }
public string Cor { get; set; }
}
Do you have any ideia how can I fix it?

Related

List of Objects and Id not getting passed to MVC Controller Method Using jQuery Ajax

Im trying to pass an Id and object of picList to the controller and it shows up null. I've looked at all the other SO solutions and changed my code to what they said and Im still getting null for both values in the controller.
So I've even tried to change the data that is being sent to the controller as such to see if that made any difference and it didn't.
in ajax call i changed the data to such
data: {"Name": "Adam"},
and added this to the controller and still nothing is getting passed.
UnitImages(string Name,..
here is what the JSON.stringify(data) looks like.
View Model
public class FileViewModel
{
public FileViewModel()
{
UnitPicturesList = new List<UnitPictures>();
}
public IList<IFormFile> Files { get; set; }
[Required]
public int AuctionId { get; set; }
public string FileLocation { get; set; }
public List<UnitPictures> UnitPicturesList { get; set; }
}
model
public class UnitPictures
{
public long ImageId { get; set; }
public string FileName { get; set; }
public string FileLocation { get; set; }
public int SortOrder { get; set; }
}
controller
[HttpPost]
public ActionResult UnitImages(long auctionId, List<UnitPictures> picList)
{ ...
}
Ajax call
function UpdateImages(auctionId, picList) {
var data = { auctionId: auctionId, picList: picList };
console.log(JSON.stringify(data));
$.ajax({
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
url: '/PhotoUploader/UnitImages',
data: JSON.stringify(data),
success: function(data){
if(data.Result == 1) {
alert("images where successfully updated.");
}else {
alert('images where successfully updated.');
}
},
error: function() {
alert("The images were not updated because of a problem.")
}
});
}
Asp.net core MVC default binding value from form, Here you can try to add [FromBody] attribute on your parameter to change the resource to bind value from body.
[HttpPost]
public ActionResult UnitImages([FromBody]string Name)
{ ...
}
Model details you can refer to Model Binding.
Try using a class that match the posted model. Something like this:
public class UnitPictures_ViewModel
{
public int AuctionId {get;set;}
public List<UnitPictures> PicList { get; set; }
}
public class UnitPictures
{
public long ImageId { get; set; }
public string FileName { get; set; }
public string FileLocation { get; set; }
public int SortOrder { get; set; }
}

ASP NET MVC passing ajax list items to controller not working as expected

I am trying to pass a list of objects to Controller using ajax, it works and shows how many items are there but shows items as null and I do not know what I am misisng.
I have this in JavaScript:
var data = {
"expediente": '#Model.NUMEMP',
"edad": '#edad',
"sexo": '#Model.SEXO',
"piezasConNotas": piezasYNotas,
//"servicio": $("#actividades").val(),
//"subServicio": $("#actividadesRealizar").val(),
"diagnostico": $("#diagnosticos").val(),
"interconsulta_esp": "",
"interconsulta": $("#interconsulta").val(),
};
console.log(data);
$.ajax({
'url': ' #Url.Action("AgregarExpedienteDental", "ServiciosMedicos")',
"data": data ,
"success": function (result) {
if (result === "1") {
//swal("Good job!", "You clicked the button!", "success");
Swal.fire('Success', 'Se ha insertado', 'success');
setTimeout('', 3000);
const myTimeout = setTimeout(myGreeting, 1500);
}
},
"error": function (response) {
}
});
this is what console.log(data) shows:
and when I send them to controller this is how it shows in the debugger:
as you can see other data is ok and the count from the list is ok but the items are going inside
as null.
I do not know what I am doing wrong? How do I solve this?
this is my C# code:
public JsonResult AgregarExpedienteDental(ExpedienteDentall data)
{
....
}
public class ExpedienteDentall
{
public string diagnostico { get; set; }
public string edad { get; set; }
public string expediente { get; set; }
public string interconsulta { get; set; }
public string interconsulta_esp { get; set; }
//public string servicio { get; set; } = "";
public string sexo { get; set; }
//public string subServicio { get; set; } = "";
public List<piezasConNotas> piezasConNotas { get; set; }
}
public class piezasConNotas
{
public string diente { get; set; }
public string nota { get; set; }
public string actividad { get; set; }
public string actividadRealizada { get; set; }
}

How tu update database using ajax and the PUT verb?

I'm trying to update a property in my database called "Estado". I'm using ajax to do it, like so:
function atualizaBD(idmarcador, novoEstado) {
$.ajax
({
url: `/api/IgnicoesAPI/${idmarcador}`,
type: 'PUT',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: JSON.stringify({ Id: idmarcador, Estado: novoEstado }),
async: true,
processData: false,
cache: false,
success: function (result) {
connection.invoke("PostMarker").catch(function (err) {
return console.error(err.toString());
});
},
error: function () {
alert("ocorreu um erro!")
}
});
}
Here is my model:
public class Ignicoes
{
public Ignicoes()
{
ListaOcorrencias = new HashSet<Ocorrencias>();
}
[Key]
public int Id { get; set; }
[Required]
public string Latitude { get; set; }
[Required]
public string Longitude { get; set; }
//estado(recusada, aceite, em avaliacao, concluido)
//public string Estado { get; set; }
[Required]
public string Estado { get; set; }
public DateTime DataInicioPropostaIgnicao { get; set; }
public DateTime DataDecisaoIgnicao { get; set; }
//lista de ocorrencias
public virtual ICollection<Ocorrencias> ListaOcorrencias { get; set; }
}
Here is my PUT method:
public async Task<IActionResult> PutIgnicoes([FromRoute] int id, [FromBody] Ignicoes ignicao)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != ignicao.Id)
{
return BadRequest();
}
else
{
var dataDecisao = DateTime.Now;
var ig = _context.Ignicoes.FirstOrDefault(ignicaoId => ignicaoId.Id.Equals(id));
if (ig != null)
{
ig.Estado = ignicao.Estado;
//ig.Estado = 0;
//ig.Latitude = ignicao.Latitude;
//ig.Longitude = ignicao.Longitude;
ig.DataDecisaoIgnicao = dataDecisao;
}
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!IgnicoesExists(id))
{
return NotFound();
}
else
{
throw;
}
}
}
return NoContent();
}
I already tried to use this code, but instead of changing the property "Estado" I changed the property "Latitude" and it worked perfectly. I don't know why this is happening. Both "Latitude" and "Estado" are the same type - String. Can somebody see the error?
Here is what appears in my output tab:
Here is the Network Analysis:
{"errors":{"Latitude":["The Latitude field is required."],"Longitude":["The Longitude field is required."]},"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"|43114da6-4594b09a6260f1a2."}
It would be easier to undestand the problem if you had added ajax http request + response logs as well (status and payloads). However, application output says 400 bad request for your API method ivocation.
Based on your resource class you have three properties declared as [Required] (except Id) : Longitude, Latitude, Estado, but in your ajax call you are passing only ID and Estado. More likely (if you are using asp.net validation) you have 400 response because of missing required properties in your ajax request body. Try to add missing properties data: JSON.stringify({ Id: idmarcador, Estado: novoEstado, string: latitude, string: longitude })

How to change variable value using PUT method?

I need to change the value of a variable when a button is clicked. For that I made a function that updates the database using ajax. Here is what I have so far:
function atualizaBD(novoEstado) {
$.ajax
({
url:`/api/IgnicoesAPI/${id}`,
type: 'PUT',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
Id : id,
Estado: novoEstado
}),
success: function (result) {
alert(result);
},
error: function () {
alert("ocorreu um erro!")
}
});
}
I have a variable called Estado and I want to change the value of that variable to a new one, novoEstado.
Here is my controller:
[HttpPut("{id}")]
public async Task<IActionResult> PutIgnicoes([FromRoute] int id, [FromBody] Ignicoes ignicao, string novoEstado)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != ignicao.Id)
{
return BadRequest();
}
var ig = _context.Ignicoes.FirstOrDefault (ignicaoId => ignicaoId.Id.Equals(id));
ig.Estado = novoEstado;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!IgnicoesExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
Right now, everytime the function an error occurs alerting "ocorreu um erro"
Here is my Model:
public class Ignicoes
{
public Ignicoes()
{
ListaOcorrencias = new HashSet<Ocorrencias>();
}
[Key]
public int Id { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
//estado(recusada, aceite, em avaliacao, concluido)
public string Estado { get; set; }
public DateTime DataInicioPropostaIgnicao { get; set; }
public DateTime DataDecisaoIgnicao { get; set; }
//lista de ocorrencias
public virtual ICollection<Ocorrencias> ListaOcorrencias { get; set; }
}
}

How to forward list containing js objects to asp.net core mvc?

I generate the js object, which looks as follows:
cartStorage = {
name: 'testcustomer',
email: 'test#gmail.com',
items: [
{
licenseName: 'Private',
licensePrice: 2
},
{
licenseName: 'Public',
licensePrice: 4
}
],
totalPrice: 6
}
Then I pass this object to mvc controller using ajax
$.ajax({
url: '/TestPayment/ChargeTest',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(cartStorage),
success: function(response){
if (response != null) {
alert(response);
} else {
alert("Something went wrong");
}
}
});
Here's the viewmodel associated with this method
namespace Web.ViewModels.Payment
{
public class Items
{
public string licenseName { get; set; }
public int licensePrice { get; set; }
}
public class PayerInfo
{
public int totalPrice { get; set; }
public string name { get; set; }
public string email { get; set; }
public Items Items { get; set; }
}
}
Here's the mvc controller method, which processes the ajax request
[HttpPost]
public ContentResult ChargeTest([FromBody] PayerInfo model)
{
String FullName = model.name;
}
But when the server executes the controller method, the model turns out to be null.
However, if I comment out the Items class and the instance creation in the PayerInfo class in the viewmodel, then the model is being forwarded successfully and all the data is stored, I'm just having the problem with the list inside of js object.
What am I doing wrong?
items in your json object is a list. So you need to change the type of Items in your c# model to a list.
namespace Web.ViewModels.Payment
{
public class Items
{
public string licenseName { get; set; }
public int licensePrice { get; set; }
}
public class PayerInfo
{
public int totalPrice { get; set; }
public string name { get; set; }
public string email { get; set; }
public List<Items> Items { get; set; }
}
}

Categories