Asp.Net MVC does not run Jquery after calling Action through "url:"

Asked

Viewed 466 times

2

I need to call an Action using Ajax and until then everything right, I make the request as follows:

confirm: function () {
            $.ajax({
                url: urlToDelete + id,
                success: function () {
                    //window.location = urlToDelete + id; <- forma que funciona porém não considero segura, não consigo usar o Request.IsAjaxRequest() no controller, tornando-o vulnerável.
                }
            });
        },

it enters Action, performs everything perfectly and returns to my View. In the view I have the following excerpt:

@if (TempData["Alerta"] != null && !String.IsNullOrEmpty(TempData["Alerta"].ToString()))
{
    <script type="text/javascript">var msg = '@Html.Raw(TempData["Alerta"])';</script>
    <script src="~/Scripts/dialog/alertNaoExcluido.js" type="text/javascript"></script>

    TempData["Alerta"] = null;
}

in this section, step to the variable 'msg' the value of my Tempdata, which would be an error message. Here’s the problem, running in this way (with Ajax) the error message does not display on the screen.

Removing the 'url' and unpacking the stretch 'window.Location' It works all the same, but it executes the alert I want. I believe the problem is with Ajax, which does not run a Jquery or Javascript after the return of a view that was made with it.

Jquery:

 $(document).ready(function () {
        $.confirm({
            icon: 'fa fa-warning text-warning',
            title: 'Atenção',
            keyboardEnabled: true,
            content: msg,
            confirmButton: 'OK',
            cancelButtonClass: 'hide',
            animation: 'top',
        });

        msg = null;
    });

1 answer

1


You could return a Jsonresult with your message, and treat it in the Success of your javascript. Something like:

Action

public ActionResult Delete(long id)
{

    /*Lógica da sua action*/

    //aqui retorna no data sua menssagem
    return new JsonResult() { Data = "Deletado com sucesso", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

Javascript

$.ajax({
url: urlToDelete + id,
success: function (data) {
    //Aqui você exibe sua mensagem, pode apendar a um modal ou topo da pagina..

    $.confirm({
        icon: 'fa fa-warning text-warning',
        title: 'Atenção',
        keyboardEnabled: true,
        content: data,
        confirmButton: 'OK',
        cancelButtonClass: 'hide',
        animation: 'top',
    });
  }
});

Browser other questions tagged

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