Calling action with AJAX, but does not return alert for view

2

In textbox Ticket , in event onChange() I call AJAX below:

$('#Ticket').on('change', function () {
var tkt = this.value;                
    $.ajax({
        url: '@Url.Action("VerificaTicket", "Oc")',
        data: { 'tkt': tkt },
        type: "post",
        cache: false
    });
 });

Calling the action below:

[HttpPost]
    public ActionResult VerificaTicket(int tkt)
    {
        Oc oc = db.Ocs.Find(tkt);
        if (oc != null)
        {
            ViewBag.IdStatus = new SelectList(db.Status, "IdStatus", "Descricao", oc.IdStatus);
            ViewBag.IdEmpresa = new SelectList(db.Empresas, "IdEmpresa", "Apelido");
            ViewBag.IdFornecedor = new SelectList(db.Fornecedors, "IdFornecedor", "Apelido");
            ViewBag.IdFaturamento = new SelectList(db.Faturamentoes, "IdFaturamento", "Apelido");
            ViewBag.IdEntrega = new SelectList(db.Entregas, "IdEntrega", "Apelido");
            ViewBag.IdProdutos = new SelectList(db.Produtos, "IdProdutos", "Descricao");                
            ViewBag.TicketExiste = "Sim";
            return RedirectToAction("Create", "Oc");                
        }
        return this.View();
    }

In view Create I'll check:

@if (@ViewBag.TicketExiste == "Sim") {
<script type="text/javascript">
    alert("Ticket já existe!");
</script>
}

Following the breakpoint, it even happens in the if of alert , but does not execute, I do not know what happens.

    
asked by anonymous 03.03.2014 / 17:55

2 answers

2

Although you are calling the method via AJAX, there is no processing that receives the return of your redirect. If the purpose of this action is just to check if the ticket already exists, I suggest you change the return to JSON and try javascript.

$('#Ticket').on('change', function () {
    var tkt = this.value;
    $.ajax({
        url: '@Url.Action("VerificaTicket", "Oc")',
        data: { 'tkt': tkt },
        type: "post",
        cache: false
    }).success(function (json) {
        if (json.ticketExiste) { //aqui verifica se existe o ticket e mostra o alert
            alert("Ticket já existe!"); 
        }
    });
 });

In your controller:

    [HttpPost]
    public ActionResult VerificaTicket(int tkt)
    {
        bool ticketExiste = false;
        Oc oc = db.Ocs.Find(tkt);
        if (oc != null)
        {
            ticketExiste = true;
        }
        return Json(new { ticketExiste });
    }
    
03.03.2014 / 19:04
0
What happens is that when the request is made by ajax in a method that returns a is ActionResult / PartialViewResult is returned the object and not that HTML that is generated when a normal request is made (by url). To resolve this problem simply change the return type to JsonResult and return the object / value you want.

    
14.03.2014 / 18:21