Asp.Net MVC does not execute JQuery after calling Action through "url:"

2

I need to call an Action using Ajax and so far everything is fine, 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 goes into Action, executes 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 snippet, I step into the variable 'msg' the value of my TempData , which would be an error message. Here's the problem, running this way (with Ajax) the error message does not display on the screen.

Removing the 'url' and uncommenting the ' window.location ' section works everything in the same way but performs the alert I want. I think the problem is with Ajax, which does not execute 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;
    });
    
asked by anonymous 15.08.2015 / 00:48

1 answer

1

You could return a JsonResult with your message, and treat the same 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',
    });
  }
});
    
15.08.2015 / 01:47