Failed to load resource: the server responded with a status of 405 - javascript

When trying to call an ASP.NET method from the client using $.ajax it gives the following error "Failed to load resource: the server responded with a status of 405 ()" knowing that the client and the API are both running on the same domain "localhost:4500", I followed the procedure I found in this Microsoft docs "https://learn.microsoft.com/en-us/aspnet/core/tutorials/web-api-javascript?view=aspnetcore-5.0 " and added the wwwroot folder to avoid the CORS issue but still can't call the API methods through the $.ajax method in javascript.
I tested the backend code through swagger and it was working just fine.
this my backend controller code:
[ApiController]
[Route("api/[Controller]")]
public class RunAnalysisController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return Ok();
}
[HttpPost("LoadFramesData")]
public IActionResult LoadFrameData([FromBody]RootObject ModelData)
{
try
{
ManageModel.CreateModel(ModelData);
return Ok(ModelData); //returning same object for testing purpose
}
catch
{
return BadRequest("Error");
}
}
}
and this my ajax function in the client side:
$.ajax({
type: "POST",
url: "api/RunAnalysis/LoadFramesData", ///// URL must be specified
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(new RootData()), //this class returns a json object
cache: false,
success: function (result) {
console.log(result);
},
error: function (ex) {
WriteToConsole(ex.responseText);
}
});

As mentioned in the comments, the issue relates the request url, change the url as below: url: "/api/RunAnalysis/LoadFramesData.
More detail information, you could refer the following sample:
Model:
public class RootObject
{
public int ID { get; set; }
public string Name { get; set; }
}
MVC View Page:
<input type="button" id="btnsubmit" value="Click Me" />
#section Scripts{
<script>
$(function () {
// LoadChart();
class RootData {
constructor(id, name) {
this.ID = id;
this.Name = name;
}
}
$("#btnsubmit").click(function () {
//var data = {};
//data.ID = "1001";
//data.Name = "Tom";
$.ajax({
type: "POST",
url: "/api/todo/LoadFramesData", ///// URL must be specified
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(new RootData(1001, "Tom")), //this class returns a json object
cache: false,
success: function (result) {
alert(result.name);
},
error: function (ex) {
alert(ex.responseText);
}
});
});
});
</script>
}
API upload method:
[Route("api/[controller]")]
[ApiController]
public class TodoController : ControllerBase
{
[HttpPost("LoadFramesData")]
public IActionResult LoadFrameData([FromBody] RootObject ModelData)
{
try
{
return Ok(ModelData);
}
catch
{
return BadRequest("Error");
}
}
The result as below:

Related

Jquery ajax post sends null when object fields are set with jquery .val() method

I am using Asp.Net Core MVC. I am trying to post an object to action result using jquery http post. When I set my object with static values, i can see all fields are set properly on client side and backend. Posted object is not null.
When I set fields of request with jquery .val() method. Request object is sent as null to backend. Where am I making mistake ?
$("#saveReport").on("click", function () { //SENDS NULL OBJECT
var request = {
BookId: $("#cmbBook").val(),
PageCount: $("#txtPageCount").val(),
Date: $("#dateReport").val(),
Note: $("#txtNotes").val(),
};
//var request = { //SENDS OBJECT PROPERLY
// BookId: 1,
// PageCount: 10,
// Note: "test"
//};
$.ajax({
type: "POST",
url: appUrl + "Report/AddUserReport",
data: JSON.stringify(request),
success: function (data) {
},
error: function (data) {
},
contentType: "application/json; charset=utf-8",
dataType: "json"
});
});
And below is backend
[HttpPost]
public ActionResult<ReadingLogResponse> AddUserReport([FromBody]AddReportModel model)
{
var response = _reportBusiness.AddReport(new AddReadingLogRequest()
{
BookId = model.BookId,
Date = model.Date,
Note = model.Note,
PageCount = model.PageCount
});
return response;
}
jquery .val() method would set the data with string type by default.You need to parse Int.Here is a simple demo like below:
1.Model:
public class AddReportModel
{
public int BookId { get; set; }
public int PageCount { get; set; }
public DateTime Date { get; set; }
public string Note { get; set; }
}
2.View:
<form>
BookID:<input id="cmbBook" type="text" />
PageCount:<input id="txtPageCount" type="text" />
Date:<input id="dateReport" />
Notes:<input id="txtNotes" type="text" />
<input type="button" id="saveReport" value="post" />
</form>
#section Scripts
{
<script>
$("#saveReport").on("click", function () { //SENDS NULL OBJECT
var request = {
BookId: parseInt($("#cmbBook").val()),
PageCount: parseInt($("#txtPageCount").val()),
Date: $("#dateReport").val(),
Note: $("#txtNotes").val(),
};
console.log(request);
console.log(JSON.stringify(request));
$.ajax({
type: "POST",
url: appUrl + "Report/AddUserReport",
data: JSON.stringify(request),
success: function (data) {
},
error: function (data) {
},
contentType: "application/json; charset=utf-8",
dataType: "json"
});
});
</script>
}
3.Controller:
[HttpPost]
public ActionResult<ReadingLogResponse> AddUserReport([FromBody]AddReportModel model)
{
//...
}

404 Not Found in AJAX post call

I'm using Spring MVC and when I do an ajax post call I get a 404. My controller looks like this:
#Controller
#RequestMapping("/mensaje")
public class MensajeController {
public MensajeController() {
super();
}
#ResponseBody
#RequestMapping(value = "/prueba", method = RequestMethod.POST)
public String prueba(#RequestParam("cuerpo") final String cuerpo) {
String b = null;
String a = null;
return b;
}
}
And the ajax call like this:
<script type='text/javascript'>
$(document).ready(function() {
$("#save").click(function(e) {
e.preventDefault();
var myEditor = document.querySelector('#editor');
var html = myEditor.children[0].innerHTML;
$.ajax({
type : "POST",
url : "/Gestion-Practicas/mensaje/prueba",
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: {'cuerpo': html},
async: false,
cache: false,
delay: 15,
success: function(data){
alert('success');
},
error: function (xhr) {
alert(xhr.responseText);
}
});
});
});
</script>
The url from where I do the ajax call is:
http://localhost:8080/Gestion-Practicas/mensaje/create.do
The url who appears in the Chrome's console after doing the ajax call is:
http://localhost:8080/Gestion-Practicas/mensaje/prueba
Summarizing, the ajax call never reaches the controller's method and I don't know why
Instead of #RequestParam use #RequestBody
#RequestParam - It's used for query parameters in request url.
#RequestBody - It's a post body payload.
Convert your String cuerpo to a class with property String cuerpo
public class PostBody{
private String cuerpo;
public String getCuerpo(){
return this.cuerpo;
}
public void setCuerpo(String cuerpo){
this.cuerpo = cuerpo;
}
}
Now your line public String prueba(#RequestParam("cuerpo") final String cuerpo)
Updated will look like public String prueba(#RequestBody final PostBody postBody).

calling a c# class method from html page

Can we call a C# method in a class from a html page??
I have a class names Crud.cs
public class Crud
{
public String generateFiles(String name)
{
return(generateHtml(name));
}
private String generateHtml(String name)
{
var filename = "C:\temp\"" + name + ".html";
try
{
FileStream fs = new FileStream(filename, FileMode.Create);
return "True";
}
catch(Exception e)
{
return e.ToString();
}
}
}
I want to call this method from a html page.I'm using a html page not a asp page.Is there any possibility to call without using ajax or if ajax also how could I call.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-3.2.1.js" type="text/javascript"></script>
</head>
<body>
<div style="align-content:center;">
<input type="text" id="HtmlName" />
<button id="btn_gen_html" onclick="createHtml()">Generate</button>
</div>
<div id="Msg"></div>
<div id="feedbackMsg"></div>
<script>
function createHtml() {
var name = document.getElementById("HtmlName").value;
$.ajax({
type: "POST",
url: "Crud.cs/generateFiles",
data: { name } ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (val) {
alert(val);
if (val == 0) {
$("#feedbackMsg").html("Success");
}
else(val==1)
{
$("#feedbackMsg").html("Sorry cannot perform such operation");
}
},
error: function (e) {
$("#feedbackMsg").html("Something Wrong.");
}
});
}
</script>
</body>
</html>
This is my code. Here I am not able to call generateFiles() method in crud class. Can I call so.And if I can How?
You can't call normal method. The method must be static and web method.
Try this:
public class Crud
{
[WebMethod]
public static String generateFiles(String name)
{
return(generateHtml(name));
}
private String generateHtml(String name)
{
var filename = "C:\temp\"" + name + ".html";
try
{
FileStream fs = new FileStream(filename, FileMode.Create);
return "True";
}
catch(Exception e)
{
return e.ToString();
}
}
}
You are missing a controler in your project.
You try to retrieve data from a cs file without a controler (or a [WebMethod])? this is impossible.
Try looking for some MVC guides, Here is one from microsoft web site
You dont have to use all that ASP component that showen there, but you can see there how to retrieve data from the server to the client.
Basic syntax
<script type="text/javascript"> //Default.aspx
function myfunction() {
$.ajax({
type: "POST",
url: 'Default.aspx/myfunction',
data: "mystring",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
});
}
Default.aspx.cs
[WebMethod]
public static String myfunction(string name)
{
return "Your String"
}
If you want to use page call without ajax: Ref
//cs file (code behind)
[ScriptMethod, WebMethod]
public static string GetLabelText(string param1)
{
return "Hello";
}
//aspx page
<script type="text/javascript">
function InsertLabelData() {
PageMethods.GetLabelText(param1,onSuccess, onFailure);
}
function onSuccess(result) {
var lbl = document.getElementById(‘lbl’);
lbl.innerHTML = result;
}
function onFailure(error) {
alert(error);
}
InsertLabelData();
</script>
If you're using ASP.NET Web Forms, there is a WebMethodAttribute you can use instead of calling .cs file directly which unsupported by AJAX due to no URL routing enabled for normal classes. The web method must be declared as static:
// if you're using ASMX web service, change to this class declaration:
// public class Crud : System.Web.Services.WebService
public class Crud : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static String generateFiles(String name)
{
return generateHtml(name);
}
private String generateHtml(String name)
{
var filename = "C:\temp\"" + name + ".html";
try
{
FileStream fs = new FileStream(filename, FileMode.Create);
return "True";
}
catch(Exception e)
{
return e.ToString();
}
}
}
Then your AJAX call URL should be changed to this (note that the web method should be exist in code-behind file, e.g. Crud.aspx.cs or Crud.asmx.cs):
$.ajax({
type: "POST",
url: "Crud.aspx/generateFiles", // web service uses .asmx instead of .aspx
data: { name: name }, // use JSON.stringify if you're not sure
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (val) {
alert(val);
if (val == 0) {
$("#feedbackMsg").html("Success");
}
else
{
$("#feedbackMsg").html("Sorry cannot perform such operation");
}
},
error: function (e) {
$("#feedbackMsg").html("Something Wrong.");
}
});
If ASP.NET MVC is used, use JsonResult to return JSON string as success result:
public class CrudController : Controller
{
[HttpPost]
public JsonResult generateFiles(String name)
{
return Json(generateHtml(name));
}
}
The AJAX call for the action method looks similar but the URL part is slightly different:
$.ajax({
type: "POST",
url: "Crud/generateFiles",
data: { name: name }, // use JSON.stringify if you're not sure
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (val) {
alert(val);
if (val == 0) {
$("#feedbackMsg").html("Success");
}
else
{
$("#feedbackMsg").html("Sorry cannot perform such operation");
}
},
error: function (e) {
$("#feedbackMsg").html("Something Wrong.");
}
});
//Perfect solution
var params = { param1: value, param2: value2}
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '../aspxPage.aspx/methodName',
data: JSON.stringify(params),
datatype: 'json',
success: function (data) {
var MethodReturnValue = data.d
},
error: function (xmlhttprequest, textstatus, errorthrown) {
alert(" conection to the server failed ");
}
});
//PLEASE menntion [WebMethod] attribute on your method.

getting null value in list when passing by ajax call to mvc controller

I am passing my list to an mvc controller but I am getting null value in the controller.But my list has values when show in alert on client side.
ajax call
$("#addTiles").click(function() {
userTiles = JSON.stringify({
'userTiles': userTiles
});
alert("Entered function.");
alert(userTiles[0].TileID);
var url = '#Url.Action("AddTiles")';
$.ajax({
type: "GET",
url: url,
data: userTiles,
success: function(d) {
if (d.indexOf('"IsSessionExpired":true') != -1) {
location.reload();
} else {
onAddTilesSuccessful(d);
}
},
error: function() {
errorInOperation();
},
contentType: "application/html; charset=utf-8",
dataType: 'html'
});
});
function onAddTilesSuccessful(e) {
$("#tilesSubmissionMsg").append(e);
}
function errorInOperation(d) {
$("#tilesSubmissionMsg").append("Something went wrong");
}
mvc controller
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
List Model
public class UserTilesVM
{
public int TileID { get; set; }
public int TopPosition { get; set; }
public int LeftPosition { get; set; }
}
List in javascript
"{"userTiles":[{"TileID":"3","TopPosition":0,"LeftPosition":0}]}"
I have also tried by sending my list with stringfy but that also doesn't work.
Use : [HttpGet] on the method AddTiles as you have used type: "GET" on the Ajax hit.
[HttpGet]
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
If Still doesn't works then try type: "POST" on Ajax hit and on method use [HttpPost]
[HttpPost]
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
You have contentType and dataType twice in your AJAX setup, with different values, which will break the AJAX call.
Keep in mind contentType is to tell the server what type of data to expect and dataType is to determine what type of data is returned, from the documentation.
Edit: I see you have edited your code!
In this case, since you are using JSON.Stringify to modify the data you are sending, you would use contentType: "application/json; charset=utf-8", as your contentType, since you are sending JSON data to the backend.
when we are trying to pass object data using ajax, we have to store data in variable and pass data directly using "data :'variable'" in AJAX to Controller Method
$("#addTiles").click(function() {
var userTiles = ({
'userTiles': userTiles
});
alert("Entered function.");
alert(userTiles[0].TileID);
var url = '#Url.Action("AddTiles")';
$.ajax({
type: "POST",
url: url,
data: userTiles,
success: function(d) {
if (d.indexOf('"IsSessionExpired":true') != -1) {
location.reload();
} else {
onAddTilesSuccessful(d);
}
},
error: function() {
errorInOperation();
},
contentType: "application/html; charset=utf-8",
dataType: 'html'
});
});
function onAddTilesSuccessful(e) {
$("#tilesSubmissionMsg").append(e);
}
function errorInOperation(d) {
$("#tilesSubmissionMsg").append("Something went wrong");
}
//Use [HttpPost] keyword for getting value which was passed by AJAX.
[HttpPost]
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
I think your list definition is not ok:
"{"userTiles":[{"TileID":"3","TopPosition":0,"LeftPosition":0}]}"
should be:
"{"userTiles":[{"TileID":"3","TopPosition":"0","LeftPosition":"0"}]}"
i have using this sequence that work fine
you have check the
contentType: "application/json",
dataType: "json",
sequence in ajax method

C# WebMethod - Send and receive same custom object as parameter

mycode:
object:
public class Person
{
private string _Nome;
private DateTime _Nascimento;
public string Nome { get { return _Nome; } }
public DateTime Nascimento { get { return _Nascimento; } }
public Person(string Nome, DateTime Nascimento)
{
_Nome = Nome;
_Nascimento = Nascimento;
}
}
page (WebMethods):
[WebMethod]
public static Person SendPerson()
{
return new Person("Jhon Snow", DateTime.Now);
}
[WebMethod]
public static string ReceivePerson(Person oPerson)
{
return "OK!";
}
javascript:
var Person;
GetPerson();
SendPersonBack();
function GetPerson()
{
$.ajax({
type: "POST",
url: "frmVenda.aspx/SendPerson",
data: {},
contentType: "application/json; charset=utf-8",
success: function (RequestReturn) {
Person = RequestReturn.d;
console.log(Person);
},
error: function (error) {
alert(error.statusText);
}
});
}
function SendPersonBack()
{
$.ajax({
type: "POST",
url: "frmVenda.aspx/ReceivePerson",
data: JSON.stringify({"oPerson": Person}),
contentType: "application/json; charset=utf-8",
success: function (RequestReturn) {
alert(RequestReturn.d);
},
error: function (error) {
alert(error.statusText);
}
});
}
I send the object to the clientside normally, but can not receive it back to server.
Why can not receive it back if the object is the same and their properties as well.
where is the problem?
Looking at the very link provided by you is possible to notice the problem.
Your code: data: JSON.stringify({"oPerson": Person}),
Right code: data: "{oPerson:" + JSON.stringify(Person) + "}",
It seems to me that you're sending a bad formatted Json to the server
Also, try adding dataType: 'json' to your call.
I solved the problem by creating a constructor with no parameters , setting all properties as string and adding the set method on all properties on my custom object (Person).
public class Person
{
private string _Nome;
private string _Nascimento;
public string Nome { get { return _Nome; } set { _Nome = value; } }
public string Nascimento { get { return _Nascimento; } set { _Nascimento= value; } }
public Person()
{
}
public Person(string Nome, DateTime Nascimento)
{
_Nome = Nome;
_Nascimento = Nascimento.ToString();
}
}
You are returning an object from webService, but your content type in ajax is json! You should create data in json format in both of your methods and return a string not object:
[WebMethod]
public static static SendPerson()
{
JavaScriptSerializer TheSerializer = new JavaScriptSerializer();
return TheSerializer.Serialize(new Person("Jhon Snow", DateTime.Now));
}
For second method just remove content-type from ajax or replace it by :
application/x-www-form-urlencoded; charset=UTF-8

Categories

Resources