Calling action with AJAX, but does not return Alert to view

Asked

Viewed 1,555 times

2

In the textbox Ticket, at the 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 check it out:

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

accompanying the breakpoint, until it passes in the if of alert, but it doesn’t perform, I don’t know what happens.

2 answers

2


Although you are calling the method by 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 handle it in 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!"); 
        }
    });
 });

On 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 });
    }

0

What happens is that when the request is made by ajax in a method that returns one is Actionresult/Partialviewresult is returned the object and not that HTML that is generated when a normal request is made (by url). To solve this problem just change the return type to Jsonresult and return the object/value you want.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.