The requested resource does not support http method 'GET' ASP MVC - ajax

I have a MVC api and are using controllers to access my data but I am using ajax and knockoutjs to call my method but I am getting the following error: The requested resource does not support http method 'GET'. I have tried using [HttpGET] at the top of my controller method but it still does not work. I am not sure how to solve this problem.
Knock ViewModel doing my api call:
vm = {
Data: ko.observable(),
Bound: 0,
Load: function () {
$.ajax({
type: "GET",
url: "../api/adusers",
contentType: "application/json;charset=utf-8",
success: function (result) {
vm.Data(ko.utils.unwrapObservable(ko.mapping.fromJS(result)));
if (!vm.Bound) {
ko.applyBindings(vm, document.getElementById("form1"));
$('#tableUsers').show();
vm.Bound = true;
}
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
})
}
}
API Controller:
public class ADUsersController : ApiController
{
[HttpGet]
public static List<Models.Users> GetADUsers()
{
return AD.GetUsers(System.Configuration.ConfigurationManager.AppSettings["NETBios"]
, System.Configuration.ConfigurationManager.AppSettings["Container"]
, System.Configuration.ConfigurationManager.AppSettings["ADServerUN"]
, System.Configuration.ConfigurationManager.AppSettings["ADServerPW"]);
}
}

You declared your controller action as static which is obviously not supported. Controller actions are instance methods. So make sure you declared your action as an instance method:
public class ADUsersController : ApiController
{
[HttpGet]
public List<Models.Users> GetADUsers()
{
return AD.GetUsers(
System.Configuration.ConfigurationManager.AppSettings["NETBios"],
System.Configuration.ConfigurationManager.AppSettings["Container"],
System.Configuration.ConfigurationManager.AppSettings["ADServerUN"],
System.Configuration.ConfigurationManager.AppSettings["ADServerPW"]
);
}
}

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

Passing a boolean value to asp.net api controller via Ajax

I am trying to pass a single boolean value via ajax to a server API.
The API action is hitted but the parameter (shuffled) is false, though I am setting it to true via Ajax.
The api controller action is this:
[HttpPost("PostShuffled")]
public IActionResult PostShuffled([FromBody]bool shuffled)
{
userSession.Shuffled = shuffled;
return Ok();
}
My Ajax call is this:
function ChangeViewMode(el) {
if (el.id == "ViewShuffled") {
$.ajax({
url: "/api/Data/PostShuffled",
contentType: "application/json",
method: "POST",
data: JSON.stringify({ shuffled: true }),
success: function () { alert("ok"); }
});
}
}
My question is what am I doing wrong?
Ok I have solved the problem this way:
Defined a new class:
public class AjaxShuffled
{
public bool shuffled { get; set; }
}
Then in my controller changed:
[HttpPost("PostShuffled")]
public IActionResult PostShuffled([FromBody]AjaxShuffled s)
{
userSession.Shuffled = s.shuffled;
return Ok();
}
And now the value is passed correctly. I had to encapsulate the boolean into a class to make it work.
The problem is that shuffled is wrapped in an object instead of sent by itself. If you only want to send a boolean value, just send true or false itself: data: true or data: JSON.stringify(true) depending on how you've configured your web service to handle input formats for boolean. On the server side you should only need the [FromBody] descriptor on the API method parameter.

Failed to post complex object in asp.net core api using jquery ajax

Failed to post complex object with list to asp.net core api using jquery ajax
Here is the Models
public class Bus
{
public int BusId { get; set; }
public string RegistrationNo { get; set; }
public IEnumerable<BusSeat> BusSeats { get; set; }
}
public class BusSeat : CoreModel
{
public int DecNumber { get; set; }
public int SeatId { get; set; }
}
Here is the Controller
[HttpPost]
public IActionResult Save([FromForm] Bus bus)
{
return Ok(bus);
}
Here is the javascript
var d = {
BusId: 1,
RegistrationNo: 'REG123',
BusSeats: [
{
DecNumber: 1,
SeatId:2,
},
{
DecNumber: 1,
SeatId: 4,
}
]
}
$.ajax({
type: 'post',
url: 'http://localhost:46060/api/bus/save',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify({ bus: d }),
success: function (data) {
},
error: function (data) {
}
});
Request is successful, but i couldn't get any data. Anything i am missing?
You don't need stringify, contentType on ajax call, and don't need [FromForm] on the mvc action.
Just pass the complex object directly on the data parameter.
$.ajax({
type: 'post',
url: 'http://localhost:46060/api/bus/save',
dataType: 'json',
data: d,
success: function (response) {
},
error: function (response) {
}
});
As long as the complex json object matches the view models you define, the binding should 'magically' work.
[HttpPost]
public IActionResult Save(Bus bus)
{
return Ok(bus);
}
This is off topic but you should think about how you construct your uris since you're building web api. You don't want to still use good old RPC style on your uri.
Think about the controller name as resource collection, and use HttpMethod as verb.
So I would create BusesController instead of BusController (Or use [RoutePrefix("api/buses")]), because I think about the resource as a collection - buses.
[Route("api/[controller]")]
public class BusesController : Controller
{
// GET api/buses
[HttpGet]
public IActionResult()
{
// Return all buses
return OK(...);
}
// GET api/buses/1
[HttpGet]
public IActionResult(int id)
{
// Return individual bus
return OK(...);
}
// POST api/buses
[HttpPost]
public IActionResult Post(CreateBusViewModel model)
{
// Create a new bus and return newly created uri of the bus
return Created(...);
}
}
You can read more about Richardson Maturity Model here!
Change the From part in the action to [FromBody] and in the ajax call for data just say
data: JSON.stringify(d)
Rather than
data: JSON.stringify({ bus: d })

How to use ajax in asp.net MVC

How can I return a class object from Ajax in asp.net MVC....???
Example:
Ajax call from html:
$.ajax({
type: 'POST',
url: '/Tutorial/Web/AlignmentRule/GetAlignmentDetails',
data: { alignmentRuleId: alignmentRuleId },
success:
function (data) {
alert(data.Id);
alert(data.alignmentData.Id);
$("#ruleName").val(data.alignmentData.Name);
$("#level").val(data.alignmentData.Id);
},
error:
function () {
alert("Server Error!!!!");
},
dataType: 'JSON',
async: false
});
and Action method in contorller is:
public virtual JsonResult GetAlignmentDetails(int alignmentRuleId)
{
var alignmentData = _allignmentRuleRepository.GetAlignmentById(alignmentRuleId);
return Json( alignmentData );
}
And I want to return a list of alignmentRule class objects also....
you can compose your return object as you want, for example, create a ViewModel as decorator to hold everything you want to pass, like:
var json = new JsonViewModel() {
alignmentData = alignmentData,
rules = yourRules
};
return Json(json);
The error is thrown because by default MVC framework does't allow you to respond to an HTTP GET request with a JSON (because of security reasons).
In order to make it work, when you retrurn Json in your action, you need to specify JsonRequestBehavior.AllowGet
[HttpPost]
public virtual JsonResult GetAlignmentDetails(int alignmentRuleId)
{
var alignmentData = _allignmentRuleRepository.GetAlignmentById(alignmentRuleId);
return Json( alignmentData, JsonRequestBehavior.AllowGet);
}
EDIT
Annotate your action with [HttpPost] attribute.
For further investigation on this topic check this article

Multiple AJAX requests in MVC3 application

The situation, I'm making multiple ajax/json requests on the same page to a controller, which returns a JsonResult.
I know this is a problem with the session state, I've added the [SessionState(SessionStateBehavior.Disabled)] attribute on my controller class, but nothing seems to work, my second ajax request just wont get the return data.
the controller:
[SessionState(SessionStateBehavior.Disabled)]
public class IndexController : Controller
{}
the two json methods:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetLatestListJSON()
{
Thread.Sleep(5000);
ArticleRepository repo = new ArticleRepository();
IList<ArticleModel> list = repo.GetLatestContent(10);
return Json(list, JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetCustomerJSON()
{
Thread.Sleep(5000);
CustomerRepository Repo = new CustomerRepository();
IList<Customer> cust= Repo.GetCustomer();
return Json(cust, JsonRequestBehavior.AllowGet);
}
The second ajax call, the other one is very similar, I never get to see the 'succes'-alert.
<script type="text/javascript">
$(document).ready(function () {
alert('before');
$.getJSON("/Index/GetCustomerJSON", null, function (data) {
alert('succes');
$("#loadingGifVideo").hide();
$.each(data, function (index, mod) {
});
});
});
Thanks guys :)
If you put a break-point in your GetCustomerJSON method and run this in Visual Studio does the method ever get called? It does
EDIT
Try switching from getJSON to the ajax method so you can capture any errors. Like so:
$.ajax({
url: "/Index/GetCustomerJSON",
dataType: 'json',
data: null,
success: function (data) { alert('success'); }
error: function (data) { alert('error'); }
});
Do you get an "error" alert?

Resources