Gerardo
Gerardo

Reputation: 369

Send alert box if controller doesn´t found results

I have a Controller like this:

public string GetTareasCalendario(TareaModel model) {
    var tareas = ag.ConsultarAgenda(model);

    var eventos = new {
        Asignados = new List < TareaCalendarioModel > (),
        NoAsignados = new List < TareaCalendarioModel > ()
    };

    foreach(var x in tareas) {
        //some code there
    };

    if (x.FechaInicioTarea != null && x.FechaFinTarea != null) {
        eventos.Asignados.Add(tareaCalendario);
    } else {
        eventos.NoAsignados.Add(tareaCalendario);
    }
}

return JsonConvert.SerializeObject(
    eventos,
    Formatting.Indented,
    new JsonSerializerSettings {
        ContractResolver = new CamelCasePropertyNamesContractResolver()
    });
}

this is executed with Ajax call like:

$.ajax({
    type: 'GET',
    url: "/Agenda/GetTareasCalendario/",
    data: {
        //Some data there
        ....
    },
    dataType: 'json',
    success: function (eventos) {
        refreshCalendarEvents(eventos.asignados);
        addEvents(eventos.noAsignados, true);
    }, error: function () {
        alert('Something is wrong, please try again.');
    }

but now I want to know how to set message if I have 0 results of my query. As you can see I have error into ajax, but how can I set something if I have zero results? Regards

As Yamamoto comment I try to use:

if (!$.trim(eventos.length === 0)) {
    alert("No results found");
}

But it just don´t pass to alert box in debugenter image description here

Results of console.log(eventos)enter image description here

Upvotes: 1

Views: 34

Answers (2)

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

In this case you want to check empty array presence in eventos.asignados, you need to use $.isEmptyObject in success function part like this:

$.ajax({
        type: 'GET',
        url: "/Agenda/GetTareasCalendario/",
        data: {

          //Some data there
           ....
        },
        dataType: 'json',
        success: function (eventos) {
            if ($.isEmptyObject(eventos.asignados && eventos.noAsignados)) {
                alert("No results found");
            } 
            else {
                refreshCalendarEvents(eventos.asignados);
                addEvents(eventos.noAsignados, true);
            }
        }, error: function () {
            alert('Something is wrong, please try again.');
        }
});

NB: The same check with if-condition can apply to eventos.noAsignados as well (edit: both of them can be combined in a single if-condition).

Upvotes: 1

Gerardo
Gerardo

Reputation: 369

It works now as @Tetsuya Yamamoto comment I use

($.isEmptyObject(eventos.asignados))
{ 
alert('No values recevied from controller')
}

Upvotes: 0

Related Questions