e.herrera e.herrera - 3 months ago 13
HTTP Question

how can i send a http to my ajax from the controller?

How can send a Http ok and error to my ajax from the controller?
for example a httpstatuscodeokay and httpstatuscodebadrequest
because when i put inspect in my browser say impresion.js 304 not modified



$(document).ready(function () {
$("#confirmacion-validar-impresion").click(function (e) {
e.preventDefault();
var form = $("form#ValidarImpresion").serializeArray();

$.ajax({
type: "POST",
dataType: "json",
url: '/FotoCarnet/ValidarImpresion',
data: form,
success: function (response) {
$("#modal-confirmacion-carne-impreso").modal('toggle')
timedRefresh();
},
error: function (response) {
alert("Carné no impreso")
}
});

$("#confirmacion-reimprimir-carnet-modal").modal('hide');
window.onbeforeunload = false;
});
});

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ValidarImpresion(FormCollection form)
{
//some query
if (queryBeneficiario.Count() > 0)
{
beneficiario = queryBeneficiario.First();
beneficiario.impreso = true;
_dbContext.SaveChanges();
return Json(new {sucess= true , HttpStatusCode.OK});
}
else
{
Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
return Json(new { success = false });
}
}

<div class="modal fade" id="confirmacion-reimprimir-carnet-modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Validar Impresion</h4>
</div>
<div class="modal-body">
<p><h4>El Carné fue impreso correctamente?</h4></p>
</div>
<div class="modal-footer">
<form id="ValidarImpresion" name="ValidarImpresion" action="#" method="post">
@Html.AntiForgeryToken()
<input type="hidden" name="cedula" value="@ViewBag.cedula" />
<button id="confirmacion-validar-impresion" type="submit" class="btn btn-success">Sí</button>
<button id="impreso-incorrectamente" type="button" class="btn btn-danger" data-dismiss="modal">No</button>
</form>
</div>
</div>
</div>
</div>




any idea?

Answer

You can just return HttpStatusCodeResult (like 500) in yor action on error.

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ValidarImpresion(FormCollection form)
        {
   //some query
            if (queryBeneficiario.Count() > 0)
            {
                beneficiario = queryBeneficiario.First();
                beneficiario.impreso = true;
                _dbContext.SaveChanges();
                return Json(new {sucess= true , HttpStatusCode.OK});
            }
            else
            {
                Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
                return new HttpStatusCodeResult(500);
            }
        }