0

I'm new to Asp.net combined with Javascript and I can't figure out what to put inside 'url' to get the data from my controller (from entity framework database I created). I keep getting the Error alert because getting data doesn't succeed.

My controller (Controllers/Api/QuestionsController)

namespace Pasapalabra.Controllers.Api
{
    public class QuestionsController : ApiController
    {
        private PasapalabraContext db = new PasapalabraContext();

        // GET: api/Questions
        public IList<Question> GetQuestions()
        {
            var questions = db.Questions.ToList();
            return questions;
        }

        // GET: api/Questions/5
        [ResponseType(typeof(Question))]
        public IHttpActionResult GetQuestionById(int id)
        {
            Question question = db.Questions.Find(id);
            if (question == null)
            {
                return NotFound();
            }

            return Ok(question);
        }
    }
}

My View (Views/Questions/Index.cshtml)

        function keepPlaying() {
            var questions = getQuestions();
            if (questions.length !== 0) {
                getRandomQuestion('A');
            } else {
                gameOver();
            }
        }

        function getQuestions() {
            $.ajax({
                url: '/api/Questions/',
                type: 'GET',
                dataType: 'json',
                success: function (data) {
                    return data;
                },
                error: function (error) {
                    alert("Error");
                }
            });
        }
  • Are you missing some routing? – Wouter van Vegchel Jul 06 '17 at 10:19
  • Routeconfig.cs redirects to another controller (also called QuestionsController, but this one is just for view, it's not api and isn't inside Api folder so I don't think it's the problem?): routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Questions", action = "Index", id = UrlParameter.Optional } ); –  Jul 06 '17 at 10:24

1 Answers1

-1

Please change your ajax call as below;

function getQuestions(callback) {
        $.ajax({
            url: '/Questions/GetQuestions',
            type: 'GET',
            dataType: 'json',
            success: function (data) {
                callback(data);
            },
            error: function (error) {
                alert("Error");
            }
        });
    }

Second part of the problem is you cannot return from an async call like that;

function keepPlaying() {
        getQuestions(function(questions){
        if (questions.length !== 0) {
            getRandomQuestion('A');
        } else {
            gameOver();
        }
      });
    }
Volem
  • 616
  • 3
  • 15
  • Thanks, still doesn't work though, now it just says: Failed to load resource: the server responded with a status of 404 (Not Found) –  Jul 06 '17 at 10:14
  • Is it working on the browser? I mean something like http://localhost/api/Questions/GetQuestions Also, try without API since you don't have route prefix. I modified the answer again – Volem Jul 06 '17 at 10:30
  • Moved getQuestions to the non-api questions controller. Now I am still getting the error alert but the console in browser doesn't say 404 not found anymore. Now it simply says: "Uncaught TypeError: Cannot read property 'length' of undefined". So I still can't get my db data. Man how difficult can this really be? :( Thanks for your help man –  Jul 06 '17 at 10:41
  • This means that we solve the problem. Now you have another one. Check my answer again – Volem Jul 06 '17 at 11:43
  • It may require some modification maybe :) I am not debugging your code. See the informative async in javascript link https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Volem Jul 06 '17 at 11:48
  • Thanks man, it gives me no errors in the console now, although it's still throwing error alert. Can't get the data, but nevermind I'm gonna do this in js alone first and then will ask again about how to implement the server-side asp.net. Thanks for your help! –  Jul 06 '17 at 12:28