Why the Ajax http get doesn't retrive json? - json

I need to retrieve JSON or HTML from my MVC controller by an Ajax call.
The question is why that below doesn't work with a GET request ?
$.ajax({
url: url,
type: "POST", //It works but doesn't work with GET
success: function (data) {
...
}
});
public ActionResult Index()
{
if (User.Identity.IsAuthenticated)
{
...
return View(selectedUser);
}
return Json(new { Error = Messages.AUTHENTICATIONEXPIRED });
}
With HTTP GET it get nothing instead the Json Object.
The Action method is executed successfully.
Is there a technical reason that I don't know? is there another way to make it work without making a POST call?
Thanks

When returning Json through GET, you have to add JsonRequestBehavior.AllowGet :
return Json(new { Error = Messages.AUTHENTICATIONEXPIRED }, JsonRequestBehavior.AllowGet);
More info there.

Related

ASP MVC Areas and JSON POST

I have a project with areas and would like to post a view model as JSON to a controller method.
This is what I have, with performance being generated in the default area and passed to the view in area SeatSelection:
$("#addToCartButton").click(function () {
var json = #Html.Raw(Json.Encode(performance));
$.ajax({
url: 'https://#(Request.Url.Host)/SeatSelection/Home/AddToCart',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
}
});
});
And the action method for testing:
[System.Web.Http.Route("SeatSelection_AddToCart")]
[System.Web.Http.HttpPost]
public JsonResult AddToCart(PerformanceViewModel performance)
{
return Json(performance.Name);
}
I created the following route:
context.MapRoute(
"SeatSelection_AddToCart",
"SeatSelection/Home/AddToCart",
new { action = "AddToCart", controller = "Home", id = UrlParameter.Optional },
namespaces: new string[] { "myProject.Areas.SeatSelection.Controllers" }
);
But all I get is a internal server error 500. I also tried to use [FromBody] and setting a breakpoint to the method, but it is not invoked. I can't figure out what's wrong or missing, please help.
UPDATE
This is the json / performance:
PerformanceID=00000000-0000-0000-0000-000000000000&Name=Performance+15&StartDate=%2FDate(1360364400000)%2F&EndDate=%2FDate(1500328800000)%2F&LatestDateBookable=%2FDate(1450911600000)%2F&Organizer=Organizer+15&Location=Location+15&Availability=75&IsFull=false&IsBookable=true&HasPrice=true&BookableSeats=11&BookedSeats=94&Description=Description+of+Performance+15&Price=443
I found an error: "invalid json primitive: performanceid"
First of all, I would recommend you to use #Url.Action helper method instead of generating url like this: https://#(Request.Url.Host)/SeatSelection/Home/AddToCart.
Secondly, always validate params which comes from the browser. return Json(performance.Name) looks suspicious. What is performance will be null? This might be a problem of your internal server error 500.
If this is not a problem then try to send string instead of JSON to the server and validate and parse JSON on the server side.
You can use Url.Action method like this. I suppose SeatSelection is an area in your project.
$.ajax({
url: '#Url.Action("AddToCart", "Home", new { Area = "SeatSelection"})',

ASP.NET MVC Ajax Call not returning Json data from controller

I'm working on an ASP.NET MVC application where I would like to call a controller method via Ajax and have it return an array from the controller in Json format.
Controller:
public class HomeController: Controller
{
public JsonResult GetArray() {
// Code for getting array here
// Convert array to JSON data
return Json(new { Items = ArrayName.ToList()});
}
}
Ajax Call:
$.ajax({
type: 'GET',
url: "/Home/GetArray",
dataType: "json",
success: function(result){
$(".container").append('<p>'+ result +'</p>');
}
error: function(){
alert("Data was not fetched properly");
}
});
Whenever I make this Ajax call, an error is always returned. I have set breakpoints within my controller and the values are being stored properly but I'm not sure why it won't reach the success function.
I believe MVC denies GET requests. You have to specifically allow get requests. Along with your json data, pass JsonRequestBehavior.AllowGet into your return statement.
return Json(new { Items = ArrayName.ToList()},JsonRequestBehavior.AllowGet);
I hope it's help full for you, you can use this return type
return Json(objResult, JsonRequestBehavior.AllowGet);

500 Error when using ajax to get json data

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);
}
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)

How to send multiple parameters from kendo data source read operation to WebApi controller

I have the following scenario: I have a kendo.dataSource which is populated via read request to a WebApi Controller. In addition to the read, I am sending a couple of parameters, which then I use in my controller to do some server logic. I was able to send as many simple parameters as I want via the parameterMap property of the transport function. Till now it was a simple get request. However now I need to send additional json object to the controller as a parameter. I read that I have to transform the Get request to Post and put the Json onto the body of the request but I don't know how to do it.
The code that I have so far:
var gridDataSource = new kendo.data.DataSource({
type: 'odata-v4',
transport: {
read: {
url: wave.alarmsAndEvents.api('api/alarmsAndEventsSearch/post'),
type: "POST",
data: {
SearchModel: JSON.stringify(vm.searchModel)
},
contentType: 'application/json; charset=utf-8',
},
parameterMap: function (data, operation) {
if (operation === "read") {
data.startDate = kendo.toString(vm.selectedTimeInterval.start, "G");
data.endDate = kendo.toString(vm.selectedTimeInterval.end, "G");
data.alarmsToDisplay = vm.maxRecords;
}
return kendo.stringify(data);
}
},
pageSize: vm.maxRecords,
error: function (e) {
alert(e.xhr.responseText);
}
});
The SearchModel is the thing that I want to send as JSon. The rest are simple DateTime and int parameters.
My controller:
[HttpPost]
public IQueryable<AlarmsSearchViewModel> Post(DateTime startDate, DateTime endDate, int alarmsToDisplay, [FromBody]JToken jsonbody)
{
....
return something;
}
I end up with Not Found 404, but I am pretty sure that I have messed up the parameters. And from the Network window I can see that the json object is not sent at all. Any help will be much appreciated!

AngularJS ngResource Send data to server with JSON and get response

In my angular JS app i need to send data to server:
"profile":"OLTP",
"security":"rsh",
"availability":"4",
"performance": {
"TRANSACTION_PER_SEC":1000,
"RESPONSE_TIME":200,
"CONCURRENT_CONNECTION_COUNT":500,
"STORAGE_SIZE":200,
"TOTAL_CONNECTION_COUNT":500
}
and in return i'll get
{"estimate" : 1600,"quoteid" : "Q1234"}
I was trying to do that with $resource but I am lost in syntax.
app.factory("VaaniEstimateService", function($resource) {
var requestURL = "http://128.34.32.34:8080/enquiry";
return $resource(requestURL, {callback: 'JSON_CALLBACK'}, { get: { method:'JSON'}, isArray:false });
});
Can you please provide me something to get me on the right path.
You must use JSONP method and insert JSON_CALLBACK keyword to your url as callback function.
app.factory("VaaniEstimateService", function($resource) {
return $resource("http://128.34.32.34:8080/enquiry?callback=JSON_CALLBACK", {}, {
get: {
method:'JSONP'
},
isArray:false
}).get({
profile:"OLTP",
security:"rsh",
availability:"4",
"performance.TRANSACTION_PER_SEC":1000,
"performance.RESPONSE_TIME":200,
"performance.CONCURRENT_CONNECTION_COUNT":500,
"performance.STORAGE_SIZE":200,
"performance.TOTAL_CONNECTION_COUNT":500
}, function (response) {
console.log('Success, data received!', response);
});
});
Your params will be sent as query params. Angularjs will automatically generate a global function for callback and replace its name with JSON_CALLBACK keyword. Your server must return json as javascript code by calling function that sent with callback parameter. For example, AngularJS is going to make GET request to that url:
http://128.34.32.34:8080/enquiry?callback=angular.callbacks._0?availability=4&performance.CONCURRENT_CONNECTION_COUNT=500&performance.RESPONSE_TIME=200&performance.STORAGE_SIZE=200&performance.TOTAL_CONNECTION_COUNT=500&performance.TRANSACTION_PER_SEC=1000&profile=OLTP&security=rsh
And your server must return response like that:
angular.callbacks._0({"estimate" : 1600,"quoteid" : "Q1234"});
Hope that's enough to give you an idea how jsonp works.