Method not allowed while using ajax put request asp.net mvc - ajax

I have the following AJAX request:
$.ajax({
url: "/api/newrentals",
dataType: "json",
type: "PUT",
data: columnDate
}).done(function() {
toastr.success("Rentals succesfully recorded.");
}).fail(function() {
toastr.error("Something unexpected happened.");
});
And here's my CONTROLLER:
using System.Web.Http; //I used the correct reference
public class NewRentalsController : ApiController {
[HttpPut]
public void updateRentalReturnDate(string columnDate){
var date = columnDate;
}
}
When I hit some button, the ajax request is executed but it does not reach the controller. I get the following error :
"message": "The requested resource does not support http method 'PUT'."
I have read many answers but nothing helped me. For instance, I made sure that the paramater name in ajax and in the controller should be same. I also put the [HttpPut] annotation in the controller method. What exactly am I missing here?

Related

asp.net web api methods are not getting executed

I am creating a web application in asp.net mvc with jQuery, I created a mvc application and included one web api controller, now my controller looks like the below
public class DefaultController : ApiController
{
[HttpGet]
[Route("Default/test")]
public string test()
{
return "1";
}
}
url of the application
https://localhost:44308/Home/about
but when I execute the method of my api the following error is coming
This site can’t be reached
I tried this with ajax call also but still the same problem
$.ajax({
type: 'GET',
url: 'https://localhost:44308/Default/test',
async: false,
global: false,
contentType: "application/json",
success: function (returnedData) {
console.log(returnedData)
}
});
I don't understand what I did wrong here
Change the route attribute
[Route("~/Default/test")]
public string test()
{
return "1";
}

How to correctly handle an AJAX request using Spring MVC? Why doesn't this example work in my project?

I am pretty new in Spring MVC and AJAX and I have the following problem.
Into a page my application perform this JavaScript function that perform an AJAX GET request:
function caricaDettaglioRegione(regioneSelezionata) {
var codiceRegione = regioneSelezionata.getAttribute("data-reveal-id");
var nomeRegione = regioneSelezionata.getAttribute("data-nome-regione");
alert("codiceRegione: " + codiceRegione + " - nomeRegione: " + nomeRegione);
$.ajax({
type: "GET",
data: {'codiceRegione' : codiceRegione
},
url: "riepilogoDettaglioRegione",
contentType:"application/json"
}).done(function(response) {
alert("DONE");
}).error(function(xhr) {
alert("ERROR");
manageError(xhr);
});
}
As you can see in the Http GET request is passed the value of the codiceRegione as request paramether (named codiceRegione) by this line:
data: {'codiceRegione' : codiceRegione
},
So now I want to handle this AJAX request and I have implement this controll method into a #Controller class:
#RequestMapping(value = "/riepilogoDettaglioRegione", method = RequestMethod.GET)
public String riepilogoDettaglioRegione(#RequestParam("codiceRegione") String codiceRegione, Model model) {
System.out.println("INTO riepilogoDettaglioRegione()");
return "blabla";
}
As you can see it handle the GET requesto toward previous resource (/riepilogoDettaglioRegione) and I try to retrieve the codiceRegione request parameter by #RequestParam("codiceRegione")
But it can't work and this method is not performed when the previous AJAX request is performed.
What am I missing? How can I solve this issue?
You're explicitly saying that the codiceRegione is a parameter not the request body.
So for that you will need to change your ajax call like:
$.ajax({
type: "GET",
url: "riepilogoDettaglioRegione?codiceRegione=blah",
contentType:"application/json"
}).done(function(response) {
alert("DONE");
}).error(function(xhr) {
alert("ERROR");
manageError(xhr);
});
Or wrap codiceRegione in an object and then change the annotation #RequestParam for #RequestBody.
Hope it helps.
Solved by myself.
The problem was that the project used Spring Security and that this resource have to be accessible also to not logged user so I have to insert something like this
<intercept-url pattern="/riepilogoDettaglioRegione" access="permitAll" />
into the authernticationManager configuration into the spring-security.xml file.

Ajax Routing Calling Controller Name Twice

I am trying to do a simple call to my controller via ajax. The RouteConfig has not been changed and set to the default values. When I make ajax call, the Url that is requested in the "Network" debugging tools is:
'http://localhost:59275/Leaderboard/Leaderboard/GetPosition'
This is causing a 404 because the Controller, Leaderboard, is being added into the Url twice. The correct url should be
'http://localhost:59275/Leaderboard/GetPosition'
My ajax call is as follows:
$.ajax({
url: 'Leaderboard/GetPosition',
type: "GET",
dataType: 'xml',
success: function (data) {
$('#results').html(data);;
}
});
and my controller is as follows:
public class LeaderboardController : Controller
{
[Webmethod]
public static DataTable GetPosition()
{
// do stuff
}
}
If the root URL of the page that request the ajax is "Leaderboard" then the url on the ajax call should only "GetPosition"
Or you can use "/Leaderboard/GetPosition" with "/" in front
Use Url.Action helper for generating correct url.
Change this:
url: 'Leaderboard/GetPosition'
to this:
url: '#Url.Action("GetPosition","Leaderboard")'

Jquery ajax call will not reach succes function

Pulling out my hair. Countless hours trying to get ajax call to work...
Jquery:
function doAjaxPost(episode_id) {
alert("cc");
$.ajax({
type: "POST",
url: "http://localhost:8080/yay/episodes/remove",
data: JSON.stringify({
episode_id : episode_id
}),
dataType: 'json',
contentType: "application/json",
success: function(){
alert("o");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.error(errorThrown);
}
});
};
Controller:
#RequestMapping(value = "/episodes/remove", method = RequestMethod.POST)
#ResponseStatus(value = HttpStatus.OK)
public void removeEpisodeFromList(#RequestBody String episode_id) {
System.out.println("Episode_id : " + episode_id);
}
And I call the function from:
MARK AS WATCHED
It reaches the controller where the correct thing is printed out.
But then FireBug just says "SyntaxError {}" and success function alert is never called.
It probably won't affect the data being passed in, but you really don't need the JSON.stringify action on your data parameter. See http://api.jquery.com/jQuery.ajax/#example-0
Also, if you are trying to get JSON back from your spring MVC controller, you need to use the #ResponseBody annotation. This will instruct Spring to not try to render out the template. I actually wrote a blog post about getting JSON back from a spring MVC application a little while back that may help.
The section titled "Mapping the response body with the #ResponseBody annotation" here can give you more information
Also, the success() function is depreciated. The done() function should be used now. More information on that can be seen at the jquery url above.
Hope this helps!
http://benashby.com/spring/response-body-annotation

Unexpected GET request after POST on AJAX call to MVC Action

I have an action method that is invoked with POST method over AJAX. Method looks like this:
[HttpPost]
public ActionResult Save(MyModel model)
{
/// do something and save
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
What happens is that after this method is call by the $.ajax, from unknown reason follow up GET request is made to same controller and same action. This call is not made anywhere and it's probably implemented either in browser or in ASP.NET MVC as Post/Redirect/Get pattern which I don't need in this case.
Is there a way to disable this programmatically because GET counterpart of Save method is not implemented and server returns 404 with HTML contents in it.
EDIT, this is the client-side AJAX script:
function saveDonkey(donkey) {
var jsonData = JSON.stringify(donkey);
$.ajax({
url: "/Donkey/Save",
data: jsonData,
contentType: "application/json",
dataType: "json",
type: "POST",
success: function () {
fetchPage(); /// This just issues GET request to another predefined method
}
});
}

Resources