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; }
}
}
Related
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; }
}
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 })
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?
I have en array that looks like this:
[Object { OldData="(3) Lindrigt skadad", NewData="(9) Uppgift saknas", AccidentNumber=1173590}]
I make a Jquery-post as below to ASP.NET:
$.ajax({
type: "POST",
url: DataReview.BASE + "/UOS/SaveUOSChangeLog",
data: postData,
success: function (data) {
//alert(data.Result);
},
dataType: "json",
traditional: true
});
Here Is my controller:
public ActionResult SaveUOSChangeLog(List<String> values)
{
try
{
var fish = Json(new { Data = values });
return Json(new { Result = "True", ResultData = values }, JsonRequestBehavior.AllowGet);
}
catch(Exception e)
{
return Json(new { Result = "Fail", Message = "Faaaaaail" }, JsonRequestBehavior.AllowGet);
}
}
When I debug this, the value of values is [0] = "[object Object]"
How can I access the actually values from the array?
EDIT:
I have created the following model:
public class UOSChangeLogFrontEnd
{
public int AccidentNumber { get; set; }
public string OldData { get; set; }
public string NewData { get; set; }
public int Action { get; set; }
}
An my controller looks like this:
public ActionResult SaveUOSChangeLog(List<UOSChangeLogFrontEnd> values)
{
try
{
var fish = Json(new { Data = values });
return Json(new { Result = "True", ResultData = values }, JsonRequestBehavior.AllowGet);
}
catch(Exception e)
{
return Json(new { Result = "Fail", Message = "Faaaaaail" }, JsonRequestBehavior.AllowGet);
}
}
But the value count Is 0 when I debug.
Create a model like this, instead of using String as a model.
public class AccidentModel
{
public int AccidentNumber { get; set; }
public string OldData { get; set; }
public string NewData { get; set; }
}
Then used it in your action like this:
public ActionResult SaveUOSChangeLog(AccidentModel accident)
{
//..use your model
}
Try this:
Model:
public class Object
{
public string OldData { get; set; }
public string NewData { get; set; }
public string AccidentNumber { get; set; }
}
public class RootObject
{
public Object Object { get; set; }
}
Controller:
public ActionResult SaveUOSChangeLog(List<RootObject> values)
JavaScript:
[{
"Object": {
"OldData": "(3) Lindrigt skadad",
"NewData": "(9) Uppgift saknas",
"AccidentNumber": "1173590"
}
}]
I have some problem while getting the object from the controller via AJAX call.To be precise, I would like to get the object which contains property with IEnumerable type.
Class 1 :
public class ChartItem
{
public string cName { get; set; }
public string label { get; set; }
public decimal value { get; set; }
public decimal value2 { get; set; }
public string value2Cur { get; set; }
public string value2Unit { get; set; }
public string color { get; set; }
public string strokeColor { get; set; }
public string chartTitle { get; set; }
}
Class 2 :
public class ReportParameter
{
public string ReportName { get; set; }
public string DateFrom { get; set; }
public string DateTo { get; set; }
public string CountryId { get; set; }
public string RegionId { get; set; }
public string RepresentativeId { get; set; }
public string CustomerId { get; set; }
public ExportFormatType ReportFormat { get; set; }
public EReport.ChartType ChartType { get; set; }
public bool EmailFlag { get; set; }
public IEnumerable<ChartItem> chartItems { get; set; }
}
This is the controller that execute the call :
[HttpPost]
public JsonResult ReloadReportSummary(EReport.ReportParameter rptParam)
{
EMAP.WEB_Bootstrap.Helper.ViewHelper viewHelper = new ViewHelper();
IEnumerable<EReport.ChartItem> resultChart=null;
try
{
EReport.ReportParameter eRpt = new EReport.ReportParameter();
eRpt.ReportName = ((EReport.ReportName)Enum.Parse(typeof(EReport.ReportName), rptParam.ReportName)).ToString();
switch ((EReport.ReportName)Enum.Parse(typeof(EReport.ReportName), rptParam.ReportName))
{
case EReport.ReportName.CRPotentialCustomerList:
//reload the chart data
resultChart =
from cp in db.CustomerProducts
join pr in db.Products on cp.ProductID equals pr.ProductID
group cp by cp.Product.ProductDescription into grp
select new EReport.ChartItem { label = grp.Key, value = grp.Count()};
break;
case EReport.ReportName.CRCustomerProductAppMasterPivot:
//reload the chart data
resultChart =
from cp in db.CustomerProducts
join pr in db.Products on cp.ProductID equals pr.ProductID
group cp by cp.Product.ProductDescription into grp
select new EReport.ChartItem { label = grp.Key, value = grp.Count() };
break;
default:
break;
}
eRpt.chartItems = resultChart;
---EDITED----
var result = eRpt;
return Json(new { Result = "OK", Record = result },
JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { Result = "ERROR"});
}
}
And this is the AJAX call :
$.ajax({
url: urlReportSummary,
data: JSON.stringify(rptParam),
type: 'POST',
contentType: 'application/json;',
dataType: 'json',
success: function (result) {
var len = result.Record.chartItem.length;
},
error: function (ex) {
alert(ex);
}
});
Actually I would like to go through each Record.chartItem's object and do some process there. But somehow the returned record not being recognized. Below is the error :
"TypeError: result.Record.chartItem is undefined".
May I know what is the correct way to get the list of data using AJAX ?
Thanks a lot
Change the success function as below and try
success: function (result) {
var len = result.Record.chartItems.length;
},
You have misspelled the property chartItems. I think now it will work