I have a form that is sent by Ajax and stored correctly in the database. How can I make that at the time of saving, it returns the ID of that record that I just stored ?, since in another part of the document I have another form that needs that ID to edit the fields of that same record.
Method to Save (Controller)
public JsonResult GuardarPropuesta(KaizenViewModel model)
{
var estado = false;
if (ModelState.IsValid)
{
using (var bd = new Modelo())
{
FormPropuesta TempPropuesta = new FormPropuesta
{
CorreoUsuario = model.FormPropuesta.CorreoUsuario,
Nombre = model.FormPropuesta.Nombre,
FechaPropuesta = DateTime.Now,
Area = model.FormPropuesta.Area,
Aporta = model.FormPropuesta.Aporta,
SituacionInicial = model.FormPropuesta.SituacionInicial,
Que = model.FormPropuesta.Que,
QuienPropone = model.FormPropuesta.QuienPropone,
QuienBeneficia = model.FormPropuesta.QuienBeneficia,
Como = model.FormPropuesta.Como,
Cuando = model.FormPropuesta.Cuando,
FechaFinal = DateTime.Now,
FechaInicio = DateTime.Now,
Donde = model.FormPropuesta.Donde,
InversionInicial = model.FormPropuesta.InversionInicial,
IndicadorClave = model.FormPropuesta.IndicadorClave,
FechaImplementacion = DateTime.Now,
FechaEvaluacion = DateTime.Now,
Estado = FormPropuesta.estado.Revision,
BenCualitativo = 0,
BenCuantitativo = 0,
NivelEsfuerzo = 0,
Originalidad = 0,
PosibilidadReplicar = 0,
Promedio = 0,
Puntaje = 0,
Observaciones = ""
};
db.FormPropuesta.Add(TempPropuesta);
db.SaveChanges();
}
estado = true;
var result = new { respuesta = estado };
return Json(result);
}
else
{
var result = new { respuesta = estado };
return Json(result);
}
}
Ajax (Vista)
$(document).ready(function () {
$("#ContOcultar").show();
$("#AlertShow").hide();
$("#ContenedorAlerta").hide();
$("#FormPropuesta").validate({
submitHandler: function GuardarPropuesta(){
var url = "@Url.Action("GuardarPropuesta", "FormPropuestas")";
var data = $("#FormPropuesta");
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: data.serialize(),
beforeSend: function () {
$("#loader").toggleClass("loader");},
success: function (result) {
AbrirModalNuevaPropuesta();
if (result.respuesta == true) {
swal({
type: 'success',
title: '¡Propuesta creada correctamente!',
timer: 3000
})
}
else if (result.respuesta == false) {
swal({
type: 'error',
title: '¡Propuesta no se ha guardada!',
timer: 3000
})
}
$("#ContenedorAlerta").show();
//$("#ContOcultar").hide();
},
complete: function () {
$("#loader").removeClass("loader");
},
});
}
});
});
They gave me a help that through the db.SaveChanges () , this gives me the ID of that record but I could not do it.
Can you help me please?