2

I'm trying to use an ajax call to get json data about my model from my controller. I know 500 error could mean lots of things but I would like to eliminate the possibility of simple error by me.

Console gives me error of: 500 Internal Service Error. Otherwise I can access it in the url just fine but I don't get anything in the console.

Index.cshtml

function getData() {
    $.ajax({
        url: "@Url.Action("dataTransfer", "Data")",
        type: "GET",
        dataType: "json",
        success: function(data) {
            console.log(data);
        },
        error: function() {
            console.log("failed");
        }
    });
}

setInterval(function() {
    getData();
}, 10000);

DataController

public JsonResult dataTransfer()
{
    string DataProvider = "Sample";

    var model = from d in db.Data
                where d.Name == DataProvider
                select d;

    return Json(model);
}
Mr.Smithyyy
  • 2,157
  • 12
  • 49
  • 95

1 Answers1

7

500 internal error means your server code is failing, running into an exception because of bad code !

From your code, i can see a problem which could be the cause of your error.

When returning Json from a GET action method, you need to pass JsonRequestBehaviour.AllowGet as the second parameter of Json method.

public JsonResult dataTransfer()
{
    string DataProvider = "Sample";

    var model = from d in db.Data
                where d.Name == DataProvider
                select d;

    return Json(model,JsonRequestBehavior.AllowGet);
}

Usually in an ASP.NET MVC application, the GET method's are supposed to be returning a view and typically the POST method does some processing on the posted form data/ajax data and return a response, which can be JSON. But if you really want to return Json data from your GET action method, You have to explicitly specify that using the above method we did

Ofcourse, Web API's has a different concept (And implementation behind the scene)

Shyju
  • 214,206
  • 104
  • 411
  • 497