简体   繁体   中英

Insert controller data inside a div as a paragraph using JQuery ajax

I have a controller that retrieves data from a model, and want to add each bit of data retrieved inside a div called test, with the data being a paragraph within the div, however I can't get it to work.

This is my controller:

namespace MyGamesProject.Controllers
{
public class GamesController : ApiController
{
    private GamesDBEntities db = new GamesDBEntities();

    // GET: api/Games
    public IQueryable<object> GetAllGames()
    {
       var games = db.Games.Include(d => d.DailyDatas)
                    .GroupBy(d => new { d.name, d.year })
                    .OrderBy(d => d.Key.name)
                    .Select(d => new
                    {
                        d.Key.year,
                        d.Key.name
                    }
                    );
        return games;
    }

}
}

And this is the ajax I'm employing within the cshtml view page:

<div id="test"></div>

@section Scripts {
<script>
    $.ajax({
        url: "/api/Games/",
        method: "GET",
        dataType: 'json',
        success: success
    });

    function success(data)
    {
        $.each(data, function (i, val)
        {
            var $data = $('<p>' + val.name + ' ' + ' was released in ' + val.year + '</p>')
            $data.appendTo($('#test'));
        });
    }
</script>
}

When loading the page, the page is blank and adding the retrieved data inside the div as a paragraph doesn't seem to have worked, I'm unsure as to why it doesn't work. Have I structured the paragraphs within the test div incorrectly, or inserted them at the wrong point? Any help would be great.

The variable games is still a LINQ query. You need to call ToList() or ToArray() on that so that the query will be executed and give you the result items.

public IEnumerable<object> GetAllGames()
{
   var games = db.Games.Include(d => d.DailyDatas)
                .GroupBy(d => new { d.name, d.year })
                .OrderBy(d => d.Key.name)
                .Select(d => new
                       {
                        d.Key.year,
                        d.Key.name
                       }
                );
    return games.ToList();
}

Here, since we are calling ToList method, the return value of the method is a list of anonymous objects(with year and name properties). So we had to change the return type of the method to IEnumerable<object>

You can open your browser devtools(F12) -> network tab and see the ajax call being made and it's response. If everything about the url and routing is good, you should see a 200 OK response with json array in the response body. If you see a 404, that means routing is not properly setup for the url your client code is trying to access. If you see 500, that means, your server code was invoked, but crashed because of some exception happened during execution of the code. You probably will be able to see the exception details in the response tab.

Also your current code is executing the jquery selector $('#test') inside the loop. You can improve thatby caching the container element selector outside of the loop.

function success(data) {
    var $container = $('#test');
    var items = '';
    $.each(data, function (i, val) {
        items += '<p>' + val.name + ' ' + ' was released in ' + val.year + '</p>';
    });
    $container.append(items);
}

When you call /api/Games/ URL By default API Call Get Method in your api. If you want to override this you need URL Routing. if you continue with GetAllGames() then use attribute route or write a route in WebApiConfig.cs file. (also see the @Shyju comment below )

Also The variable games is a LINQ query you need to call ToList() for execute the data.

Controller:

namespace MyGamesProject.Controllers
 {
    public class GamesController : ApiController
    {
         public IHttpActionResult Get(long id)
         {
            var games = db.Games.Include(d => d.DailyDatas)
                         .GroupBy(d => new { d.name, d.year })
                         .OrderBy(d => d.Key.name)
                         .Select(d => new
                         {
                          d.Key.year,
                          d.Key.name
                         }).ToList();

         return Ok(games);
      }    
     }
    }

view page:

<div id="test"></div>

@section Scripts {
 <script>
  $(function () {
    $.ajax({
        url: "/api/Games/",
        method: "GET",
        dataType: 'json',
        success: success
    });

    function success(data)
    {
        $.each(data, function (i, val)
        {
            var $data = $('<p>' + val.name + ' ' + ' was released in ' + val.year + '</p>')
            $data.appendTo($('#test'));
        });
    }
});
</script>
}

IQueryable is just a query. It doesn't yield result. Append it with tolist(). In this case it's not giving you result bcoz there is no database context to fire IQueryable. Database context is disposed the moment control went to view.

corrected

namespace MyGamesProject.Controllers
{
    public class GamesController : ApiController
    {
        private GamesDBEntities db = new GamesDBEntities();

        // GET: api/Games
        public IHttpActionResult GetAllGames()
        {
            var games = db.Games.Include(d => d.DailyDatas)
                         .GroupBy(d => new { d.name, d.year })
                         .OrderBy(d => d.Key.name)
                         .Select(d => new
                         {
                             d.Key.year,
                             d.Key.name
                         }
                         ).ToList();
            return Ok(games);
        }

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM