How to return warning in a View if there is no data to display?

Asked

Viewed 52 times

1

I created the code below that generates a list. It checks whether the list contains any data saved in it or not. If you have data, returns a View with the list inside, if you have no data, returns null.

How to do to, rather than return null, display a warning on the page stating that there is no data to be shown?

[HttpPost]
    public ActionResult Relatorio(string ocupacaoId, string instrumentoRegistroId)
    {
        List<ProcedimentoOcupacaoRegistro> listaprocedimentoocupacaoregistro = new ProcedimentoOcupacaoRegistro().listaProcedimentoOcupacaoRegistro(ocupacaoId, instrumentoRegistroId);
        ViewBag.ocupacaoId = ocupacaoId;
        ViewBag.instrumentoregistroId = instrumentoRegistroId;
        if (listaprocedimentoocupacaoregistro.Count > 0)
        {
            return View(listaprocedimentoocupacaoregistro)
        }
        else
        {
            return null; // <<---AQUI EU QUERO ALTERAR
        }
    }

1 answer

2


I imagine you want this:

return new EmptyResult();

Documentation.

To class documentation ActionResult shows all possible return types for the view. You can even create others that better suit your needs.

There are other ways.

From what I saw the null ends up giving the same result.

Then you have to deal with view how to deal with this situation. You can send to view normal and treat there as present to the user, something like this:

@model IEnumerable<ProcedimentoOcupacaoRegistro>

@if (Model.Count() > 0) {
    ...
} else {
    <div>Não tem itens pra mostrar</div>
}

Or, more commonly, send a view different that shows the error message you want, after all show the data is a view, show that has no data to show is another view, example:

return RedirectToAction("Error", "Relatorio");

Depending on how it is mounted you can send code:

return JavaScript( "alert('Nada a mostrar');" );

Or else:

return View("SemDadosView");

I put in the Github for future reference.

Of course you need to create the view just the way you want it.

Browser other questions tagged

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