I want to make a select on the database. But I get following error (only the first rows of the error):
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below
[HttpException (0x80004005): Server cannot set content type after HTTP headers have been sent.]
System.Web.HttpResponse.set_ContentType(String value) +9752569
System.Web.HttpResponseWrapper.set_ContentType(String value) +14
System.Web.Mvc.JsonResult.ExecuteResult(ControllerContext context) +177
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +27
A part of my DBcontroller:
string sql = @"exec [results].[GetNewResults] '" + Sources + @"', '" + Searchstring + @"', '" + username + @"', '" + sessionid + @"'";
var result = dbcontext_hke.Database.SqlQuery<UnifiedResultset>(sql);
if (results == null)
{
Debug.WriteLine("results is null");
return Json(null);
}
Debug.WriteLine("results isn't null");
Debug.WriteLine(results);
return Json(results, JsonRequestBehavior.AllowGet);
A part of my js:
var url = $('#initialrequest').val();
$.ajax({
url: url,
data: {sources, searchstring},
type: 'POST',
})
.success(function (result) {
for (var i = 0; i <= (9); i++) {
try {
console.log("lenght of result is :" + result.length);
add_error(result);
console.log("result is : " + result);
add_result(result[i].header, result[i].source, result[i].subsource, result[i].description);
} catch (err) {
add_error();
}
})
.error(function (xhr, status) {
$('#error').append(xhr.responseText);
console.log(xhr.responseText);
});
Basically after some research I found this with that code as a solution for a (maybe) similar problem:
this.Context.Response.Write(response);
this.Context.Response.Flush();
May anyone explain to me what is going on there and how I can fix it (or modify the code of the other solution)?
EDIT1: I have ensured that the controller get's the information. So the error might be at the communication between controller and js. Any ideas?
EDIT2: Also adding
Response.BufferOutput = true;
at the Index() of the HomeController and the DBController doesn't change anything.
EDIT3: I identified that the Problem is with the JSON in the return. If I return a different type, it works fine. Any ideas why this happens and how to fix it?
EDIT4: The reason my code doesn't work is because the command
var result = dbcontext_hke.Database.SqlQuery<UnifiedResultset>(sql);
doesn't execute immediately I think. If I want to see what's inside result with Debug.WriteLine(result) I only get the plain sql command. Ideas?