Why am I not handling the _Layout file when I'm handling an error?

0

I'm doing an error handling using Json Result, when I displayed the error message it should display the formed page as well as it rules in the _Layout file, so the page is loading all white, does anyone know how to solve it? Below the image of how it is being displayed!

HereismyhomeController:

usingReportandoErro.Models;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingSystem.Web.Mvc;namespaceReportandoErro.Controllers{publicclassHomeController:Controller{publicActionResultIndex(){returnView();}publicActionResultTeste(){varresponse=newResponseViewModel();try{thrownewException("Oops, ocorreu um erro");
            }
            catch (Exception e)
            {
                return ErroCapturado(e);
            }
            return Json(response, JsonRequestBehavior.AllowGet);
        }

        public ActionResult ErroCapturado(Exception ex)
        {
            var response = new ResponseViewModel
            {
                Data = ex.Data,
                Sucesso = false,
                Mensagem = ex.Message
            };

            return Json(response, JsonRequestBehavior.AllowGet);

        }
    }

}

Here's my AccountViewModels:

public class ResponseViewModel
    {
        public object Data { get; set; }
        public bool Sucesso { get; set; }
        public string Mensagem { get; set; }
    }

And here's the test call view:

@{
    ViewBag.Title = "Teste";
}
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@model ReportandoErro.Models.ResponseViewModel

<h2>Teste</h2>

<script type="text/javascript">
    $(document).ready(function () {
        //debugger;
        gerandoRelatorio();
        function gerandoRelatorio() {
            $.getJSON("Home/Teste", function (response) {

                if (response.sucesso) {
                    console.log(response.data);
                }
                else {
                    alert(data.mensagem);
                }

            }).fail(function (response) {
                //Erro genérico
                alert("Não foi possível processar a sua requisição");

            });
        }
    });
</script>
    
asked by anonymous 30.01.2018 / 17:04

1 answer

2

To render the page, you need to return a View() in which case you only return Json(response, JsonRequestBehavior.AllowGet) . Always create Actions for your Ajax requests. To solve this, just create a Action only for your request, follow the code:

using ReportandoErro.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ReportandoErro.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Teste()
        {

            return View();
        }

        public ActionResult Ajax_Teste()
        {
            var response = new ResponseViewModel();
            try
            {
                throw new Exception("Oops, ocorreu um erro");
            }
            catch (Exception e)
            {
                return ErroCapturado(e);
            }
            return Json(response, JsonRequestBehavior.AllowGet);
        }

        public ActionResult ErroCapturado(Exception ex)
        {
            var response = new ResponseViewModel
            {
                Data = ex.Data,
                Sucesso = false,
                Mensagem = ex.Message
            };

            return Json(response, JsonRequestBehavior.AllowGet);

        }
    }

}

I created the Action Ajax_Teste which executes the Ajax request and returns Json .

And within the Javascript where you execute the request, you will call Ajax_Teste and not Teste :

@{
    ViewBag.Title = "Teste";
}
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@model ReportandoErro.Models.ResponseViewModel

<h2>Teste</h2>

<script type = "text/javascript" >
$(document).ready(function () {
//debugger;
gerandoRelatorio();
    function gerandoRelatorio()
    {
        $.ajax({
            method: "GET",
            url: "Home/Ajax_Teste"
        })
        .done(function (response) {
            if (response.Sucesso)
            {
               console.log(response.Mensagem);
            }
            else
            {
                alert(response.Mensagem);
            }
        })
        .fail(function(response) {
            //Erro genérico
            alert("Não foi possível processar a sua requisição");
        });
        }
    }
</script>

So, Action Teste returns its View() and Action Ajax_Teste returns its Json() .

The hint of content about asynchronous / synchronous request in the MVC standards in this question .

To display the response you can use what was already in your JS code: console.log(response.Mensagem) remembering that Javascript is Case-sensitive, you were calling if(response.sucesso) correct if(response.Sucesso) .

If you want to insert into your View, you can manipulate the DOM. Under <H2> , add the following line:

<p id="mensagem"></p>

And in your Javascript add:

$("#mensagem").text(response.Mensagem);

So he will fill in the paragraph with the message.

    
30.01.2018 / 17:53