C# Call Controller method Asp.Net MVC5 with Ajax

Asked

Viewed 2,588 times

1

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, I hope it was clear and that 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 don’t know much about Javascript and Ajax, but what I need is to recover Getdata to manipulate it. The following is a possible description of what I need, just playing on the console, if you get this later 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>

That question here served me as the basis for the question, but it didn’t work for me:

How to call a controller method from 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:

inserir a descrição da imagem aqui

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}
  • Debugging, or accessing directly to GetData() the list qry receives some value and the results are displayed?

  • So, I do not know how to directly access Getdata, I marked it in debug but it is not called, what I did was to put this method inside the Actionresult Index(), so when the page is loaded it shows the data of qry...

  • this action is in your HomeController?

  • Yes, this in Homecontroller

2 answers

1

In his GetData(), if using the 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 will not 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 doesn’t 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);
}
  • It worked partially, error 404 is gone, but in new Jsonresult(qry) you have the message; Initialize a new instance of the Jsonresultclass, and the console is empty....

  • What is the version of . Net you are using?

  • I believe this is it: <Compilation debug="true" targetFramework="4.5" />

  • So keep your controller the way it was return Json(qry, JsonRequestBehavior.AllowGet);

  • I put console.log("Something") to test and it appeared on the console, so I believe the result is blank console.log(result), I would have to show the Getdata not?

  • anything else that might help me?

Show 1 more comment

0

If you want to simply pick up (GET) the information, you have to use the attribute HttpGet in his 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 in jquery Post

$.get('@Url.Action("GetData", "Home")', function (data) {
            console.log(data);
        }).fail(function (jqxhr, status, error) {
            console.log(error);
        });
  • I put [Httpget] in Getdata() and did so: <script type="text/javascript"> $(Document). ready(Function() { $.get('@Url.Action("Getdata")', Function(data) { console.log(data); }). fail(Function (jqxhr, status, error) { console.log(error); }); }); </script> But I get this msg: GET http://local:16187/Home/Getdata 404 (Not Found)

  • @Pablotondolodevargas Switching to get is not a good solution, the post brings minimal content protection.

  • @Leandroangelo pq use the verb POST if he wants to search and not send information to the server? https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

  • @user3323405 in which controller is your Getdata action?

  • Is in Homecontroller

  • Searching saw that it can be something related to Router, this project was a template I took with Bootstrap and MVC, in it has a Routconfig class, I will give an Edit and put the code, it will help....

  • I made a change to jquery’s Get method, further specified the controller in @Url.Action

  • Same mistake....:/

  • For more information, this script is in Layout.cshtml which is the one used in Index.cshtml

Show 4 more comments

Browser other questions tagged

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