Encountering 'Error 405 - Method not Supported' while making an Ajax POST request in ASP.NET Web API

I am currently in the process of developing a straightforward Web API service that captures input data from an HTML form, converts it into JSON format, and forwards it to a Web API. My coding platform is ASP.NET Web API on Visual Studio 2017. To further elaborate, here's a snippet of my code:

This snippet showcases the controller method I'm invoking:

[HttpPost]
public AssessModel PostAssessment ([FromBody] AssessModel assess)
{
    //Performing certain actions
    return assess;
}

Here's a simplified version of the model I'm utilizing:

public class AssessModel
{
    public Guid capitalassetassessmentid { get; set; }
    public string ownerid { get; set; }

    /*... Several more properties including int, bool, etc. are listed here ...*/

    public string name { get; set; }
    public string building { get; set; }
}

Lastly, this is the Ajax call integrated within my scripts:

$("form#my-form").submit(function (e) {
    var formArray = $(this).serializeArray(); 
    var jsonObj = JSON.stringify(formArray); 

    $.ajax({
        type: "POST",
        url: "api/assessment/PostAssessment",
        data: jsonObj,
        contentType: "application/json",
        dataType: "json",
        success: function (jsonObj) {
            $("#results").html(jsonObj.d);
        }
    });
});

Hence, upon submitting a form, this ajax request gets triggered. However, upon submission, instead of sending my JSON as intended to the controller method, I encounter an 'Error 405 - Method not Allowed'. I find this puzzling since I should be permitted to utilize a POST verb with a HttpPost-tagged controller method.

Additionally, it's noteworthy to mention that my form tag appears like this:

<form id="my-form" class="form" method="POST">

Any insights or suggestions? Require additional clarification? Feel free to inform me.

Answer №1

Test it out

let information = {};
let formEntries = $('form#my-form').serializeArray();
for(let i in entries)
{
    information[formEntries[i].name] = formEntries[i].value;
}
let jsonData = JSON.stringify(information);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to incorporate an if else condition using the <?php if($loggedin): ?> statement within JavaScript code to display a button push or pop response from the server side?

I would like to verify this php if condition code ''<?php if($loggedin) : ?>'' inside JavaScript code in order to display one of the buttons, either push or pop. I want to keep this button hidden from the client side by embedding ...

Exploring the world of jQuery's fade transitions paired with the convenience

I've implemented a code snippet for user login via Ajax. However, I'm facing an issue where the fade effects are overlapping with each other due to the quick processing of the request. Despite receiving data to display, I am stuck with just the " ...

Removing a feature through AJAX in CodeIgniter

Issue Resolved.. I have updated my code accordingly.. Thanks to everyone for the help Description: My code displays an array of message traces (each message is displayed in a grey panel). Users can delete unwanted messages by clicking on the delete button ...

Error encountered while attempting to save files automatically using Selenium WebDriver with C# in Firefox

I developed this code using C# to enable Firefox to automatically save the file without displaying the save as dialog box. FirefoxProfile profile = new FirefoxProfile(); profile.SetPreference("browser.download.manager.alertOn ...

Troubleshooting Issue with Google Analytics Event Sending upon Ajax Success Failure

I've created a Process Transaction Knockout method that retrieves a transaction status. Depending on this status, I want to trigger an event in analytics.js. Despite using analytics-debug.js and seeing "Send finished" in the console, the event never a ...

"Server request with ajax did not yield a response in JSON format

http://jsfiddle.net/0cp2v9od/ Can anyone help me figure out what's wrong with my code? I'm unable to see my data in console.log, even though the network tab in Chrome shows that my data has been successfully retrieved. Here is my code snippet: ...

Tips for sending an Ajax request to a separate URL on the same server

When making an ajax request to my server, I use the following code: var data = ''; $.ajax({ type: 'GET', url: 'api/getnews/home/post/'+title, data: data, datatype: 'json', success: f ...

Updating the ContextKey of the DynamicPopulateExtender based on the selected value from a DropDownList dynamically

I am facing an issue with my DynamicPopulateExtender control. I need it to render HTML based on the value of an asp:DropDownList. The problem lies in writing the JavaScript code that can fetch the dropdown value, assign it to the DynamicPopulate control&ap ...

Utilizing PrimeFaces for handling multiple DataTables with rowselect event handling

In my project, I have a dynamic list of data tables and I am attempting to enable row selection for a single row in each table. The issue I am facing is that the code provided below only works when the user selects a row in the last data table. It seems li ...

Is it beneficial to consolidate masterdata calls into a single call?

Our application is built using REST with an Angular 2 client. We frequently make calls to master data APIs such as country and agreement during login, totaling around 6-7 calls. From a performance standpoint, would it be beneficial to consolidate these c ...

Creating session variables in Joomla using checkboxes and AJAX

I'm currently working on implementing session variables in Joomla with AJAX when checkboxes are selected. Below is the code snippet from select_thumb.ajax.php file: $_SESSION['ss'] = $value; $response = $_SESSION['ss']; echo ...

"422 (Unprocessable Entity) Error When Submitting a Form in Rails Application

I recently delved into the world of ruby on rails a few days back. My current challenge involves transferring data from html tags to a ruby function using ajax. Below is the error message that has been giving me trouble: POST http://localhost:3000/ajax/o ...

Transferring session data through AJAX in PHP

I'm currently developing an app using PhoneGap. However, PhoneGap only supports HTML, CSS, and JS, not PHP. This led me to the workaround of placing the PHP file on a remote server and using AJAX to call it via the server's URL. My issue now is ...

JSON Date Format

I'm facing an issue where I am unable to retrieve the current date using new Date() because it is in JSON format. This particular code was written using MVC C#. The date appears as \/Date(1531364413000)\/. The dates stored in the database ...

Ways to identify a group of elements within a page object without creating an individual element for each one

I am looking to access a series of elements with similar IDs ranging from 1 to 47. Rather than individually specifying each element, is there a more efficient way to create an array or list for easy iteration? [FindsBy(How = How.Id, Using = "ElementId1")] ...

Using TinyMCE editor to handle postbacks on an ASP.NET page

I came up with this code snippet to integrate TinyMCE (a JavaScript "richtext" editor) into an ASP page. The ASP page features a textbox named "art_content", which generates a ClientID like "ctl00_hold_selectionblock_art_content". One issue I encountered ...

The array is giving back null values

When making a POST request with AJAX and sending data in JSON format, everything seems to be working fine until trying to print out a specific index value from the decoded array, which returns null. What could be causing this issue? Here's the AJAX re ...

The conversion of a 2D json array into a string is mistakenly performed

On hand is an outer array that contains 2 arrays within it, making it a 2-dimensional array. This is how the array is initialized: $outerArray = array(); $nestedArray = array("first", "second", "third", "fourth"); $outerArray[] = $nestedArray; $nest ...

Using Ajax.BeginForm with BeforeSend functionality

My MVC website has multiple Ajax.BeginForm elements, and I am looking to handle the beforeSend event of my Ajax calls. While the code below works for manual jquery ajax calls, it does not seem to work with the Ajax.BeginForm helpers: $.ajaxSetup({ &a ...

Encountering a hiccup during a join linq query操作oops!

I am currently working on this code snippet: public ActionResult JoinSupToPro() { SupplierDBContext dbS = new SupplierDBContext(); var innerJoinQuery = from pro in db.Products join sup in dbS.Suppliers on pro.SupplierId equals sup ...