C # Calling the Asp.Net MVC5 Controller method with Ajax

0
Hello, I have a method called GetData() in my HomeController that returns a JSON, I would like to pass the data to my View, but it always comes empty, I'm starting as a developer, and I'm already a few days into it, been clear and someone can help me ...

[HttpPost]
public JsonResult GetData()
{
    List<Dados> qry = new List<Dados>();

    using (AGPEntities md = new AGPEntities())
    {
        qry = (from s in md.Painel_Grafico
               select new Dados
               {
                   id_admAtribuido = s.id,
                   admAtribuido = s.admAtribuido,
                   quantidade_admAtribuido = (int)s.quantidade_admAtribuido

               }).ToList();
    }
    return Json(qry, JsonRequestBehavior.AllowGet);
}

I do not understand much of JavaScript and Ajax, but what I need is to retrieve the GetData data to handle. The following is a possible description of what I need, just playing on the console, if I can, then I turn around.

<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
               type: "POST",
               url: '@Url.Action("GetData")',
               data: //O que colocar aqui?
               success: function (result) {
                   console.log(result);                      
               },
               error: function (result) {
                      console.log("erro");
               }
            });
    });
</script>

This question was the basis for the question, but it did not work for me:

How to call a controller method using Ajax using MVC5 in visual studio?

Thanks in advance ...

[EDIT] When I put the GetData code inside the ActionResult Index () I get the following return:

publicclassRouteConfig{publicstaticvoidRegisterRoutes(RouteCollectionroutes){routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}
    
asked by anonymous 04.01.2018 / 14:29

2 answers

0

If you just want to get the information, you have to use the HttpGet attribute in your Action .

    [HttpGet]
    public JsonResult GetData()
    {
        List<Dados> qry = new List<Dados>();

        using (AGPEntities md = new AGPEntities())
        {
            qry = (from s in md.Painel_Grafico
                   select new Dados
                   {
                       id_admAtribuido = s.id,
                       admAtribuido = s.admAtribuido,
                       quantidade_admAtribuido = (int)s.quantidade_admAtribuido

                   }).ToList();
        }
        return Json(qry, JsonRequestBehavior.AllowGet);
    }

And use Get instead of jquery Post

$.get('@Url.Action("GetData", "Home")', function (data) {
            console.log(data);
        }).fail(function (jqxhr, status, error) {
            console.log(error);
        });
    
04.01.2018 / 14:44
0

On your GetData() , if you are using AspNetCore or later, change the return to the specialized type JsonResult()

[HttpPost]
public JsonResult GetData()
{
    List<Dados> qry = new List<Dados>();

    using (AGPEntities md = new AGPEntities())
    {
        qry = (from s in md.Painel_Grafico
               select new Dados
               {
                   id_admAtribuido = s.id,
                   admAtribuido = s.admAtribuido,
                   quantidade_admAtribuido = (int)s.quantidade_admAtribuido

               }).ToList();
    }
    return new JsonResult(qry);
}

In your JavaScript, if you are not going to send any information to the server, there is no need to declare the date attribute:

<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
               type: "POST",
               url: '@Url.Action("GetData","Home")',
               //data: //O que colocar aqui? (remover)
               success: function (result) {
                   console.log(result);                      
               },
               error: function (result) {
                      console.log("erro");
               }
            });
    });
</script>

If it still does not work you can change the Controller type to ActionResult.

[HttpPost]
public ActionResult GetData()
{
    List<Dados> qry = new List<Dados>();

    using (AGPEntities md = new AGPEntities())
    {
        qry = (from s in md.Painel_Grafico
               select new Dados
               {
                   id_admAtribuido = s.id,
                   admAtribuido = s.admAtribuido,
                   quantidade_admAtribuido = (int)s.quantidade_admAtribuido

               }).ToList();
    }
    return Json(qry, JsonRequestBehavior.AllowGet);
}
    
04.01.2018 / 15:11