Sending a complex JavaScript object to the MVC controller with a consistent 400 response code

Once again facing another MVC issue. Someday, I'll look back at my "MVC learning days" and smile.

So here's the problem - a constant 400 response. Despite reading numerous posts on SO, I just can't seem to get my logic working. Maybe if I show you the logic, someone could help me out.

Controller:

public JsonResult CreateExtendedProperty(ExtendedPropertyDefinitionViewModel extendedPropertyDefinitionViewModel)
{

   //I started with JsonResult as ActionResult, but no luck yet.
    var p = extendedPropertyDefinitionViewModel;

    //Temp
    //return Json(new { Success = false, ErrorMessage = "Error creating property" });
}

The Ajax/Javascript:

        var extendedPropertyDefinition = JSON.stringify({
            DefinitionId: '0',
            Title: propertyInfo["Title"],
            OrganisationId: '0',
            Organisation: '',
            TypeId: propertyInfo["TypeId"],
            SortOrder: 0,
            IsEnumerated: propertyInfo["IsEnumerated"],
            AllowMultiSelect: propertyInfo["AllowMultiSelect"],
            IsDate: propertyInfo["IsDate"],
            LastUpdatedBy: "",
            LastUpdatedDateTime: new Date().toISOString(),
            CreatedBy: "",
            CreatedByDateTime: new Date().toISOString(),
            Options: {
                OptionId: '0',
                Option: '',
                OptionValue: '',
                SortOrder: 0,
                LastUpdatedBy: '',
                LastUpdatedDateTime: new Date().toISOString(),
                CreatedBy: '',
                CreatedByDateTime: new Date().toISOString(),
            }
        });

        $.ajax({
            url: "<%= Url.Action('CreateExtendedProperty', 'Organisation') %>",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            //traditional: true,
            type: 'POST',
            data: extendedPropertyDefinition,
            success: function(e) {
                alert('success');
                //Rebuild Grid? 
            },
            error: function(e) {
                alert('request failed (500)');

            }
        });

The payload: https://i.sstatic.net/1xkYU.png

Hoping someone can guide me in the right direction, any help would be greatly appreciated.

Regards,

Answer №1

Simply put, in order to extract the answer from the comments, you must make sure that

<%= Url.Action('CreateExtendedProperty', 'Organisation') %>
is properly compiled. If it resides in a separate JS file, you need to transmit it from your view. Otherwise, there may be an alternative issue (if you are utilizing Razor syntax, it should look something like
@Url.Action("CreateExtendedProperty", "Organisation")
)

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

JavaScriptCore now includes the loading of AMD modules

I am trying to incorporate a JavaScript module into JavascriptCore on iOS. To achieve this, I am fetching the file's text through a standard HTTP request on the iOS platform. Once I have obtained the entire string, I plan to parse it into the JSconte ...

Guide on building a multi-page application using Vue or React

I find myself a bit confused when it comes to single-page applications versus multi-page applications. While I am aware of the difference between the two, I am struggling with creating a MPA specifically. Up until now, I have built various apps using Rea ...

Using PHP to create multiple div elements and then concealing them all

I'm having an issue with the hide feature not working. My intention is to hide each dynamically generated div and gain control over them, but the problem seems to lie in the div id incrementing. Any assistance would be greatly appreciated! <?php $ ...

Notification issues in Vue with Firebase Cloud Messaging while in foreground

I have been working on implementing FCM in my Vue PWA application. I have successfully configured background notifications, but I am facing issues with handling notifications when the app is open. Here is the code I am using. src/App.vue import firebase ...

What is the best way to transfer static assets from an npm package to a nuxt project?

Has anyone successfully sent assets from an npm package to a nuxt application before? I have a vue component within an npm package with the following structure: -src/ -assets/ -noun-filter.svg In this npm package, the vector image is included in the v ...

What is causing the 'transitionend' event to trigger multiple times?

Currently, I'm honing my JavaScript skills by taking on the 30 days of JavaScript challenge. I'm puzzled by why the 'transitioned' event is triggered twice in the code snippet below. My CSS only contains one property called transform, ...

Struggling to reflect changes in the database using the updated value in the localStorage

I have a table where the td is set to contenteditable. To update the value of the td in my database, I decided to use localStorage. When the save button is clicked, the inputted value in the td will be saved to localStorage and retrieved via AJAX to replac ...

Is it possible to create a clickable link within a RichTextControl in a WPF application?

I am looking to create a clickable text feature similar to webpages in WPF. The control should consist of non-functional text for display, as well as some clickable parts. Think of it like Wikipedia. However, this is for an independent standalone offline ...

Sorting data by percentages in AngularJS

I am currently facing an issue with sorting percentages in a table column. Despite using methods like parseFloat and other AngularJS (1.5.0) sorting techniques, the percentages are not being sorted as expected. [ {percentage: 8.82} {percentage: 0. ...

Using AngularJS $http.jsonp() method to interface with Google Maps Distance Matrix API

I am currently working on integrating the Google Maps Distance Matrix API into my project to calculate distances between two points using specific coordinates. My implementation involves AngularJS and the $http.jsonp() method to make requests to the API: ...

A guide on verifying text obtained from an API endpoint using c#

I am currently developing an automation test that involves interacting with an endpoint URL 'https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1'. Upon accessing this endpoint, certain text is displayed. Can someone advise me on how I ...

Session is required for req.flash() function in node.js to work properly

I recently started working with Node.js and I'm encountering an issue with sessions. I developed a simple application and tried to run it locally, but ran into some errors. Below are the details of my code along with the error messages: BAPS.js (app. ...

What might be causing the hasOwnProperty(key) method in JSON to return false?

I have successfully implemented a method to loop through the JSON data provided below: {"dummmysetsJSONArr":[{"entryID":"1","distance":"100","calories":"50"},{"entryID":"2","distance":"200","calories":"100"},{"entryID":"3","distance":"300","calories":"150 ...

removing an item from a nested array through the use of the filter() method

I have been struggling to remove an element with a specific ID from a nested array. Are there any suggestions on how to effectively utilize the filter() method with nested arrays? The goal is to only eliminate the object with {id: 111,name: "A"}. Below ...

Determining the file path relative to the project/src directory in Node.js

Currently, in my node.js project I am utilizing log4js and aiming to include the file name where the log record was added. However, when using __filename, it provides me with the absolute path. var logger = log4js.getLogger(__filename) This results in lo ...

Is it possible to monitor connections using HTTP?

There is ongoing debate about whether HTTP is connection-oriented or connectionless. From what I understand, HTTP maintains a connection only long enough to transmit immediate requests. Recently, I had a conversation with a Microsoft certified architect ab ...

ajax. Sorry, the page you are looking for cannot be located

I'm working with C# asp.net mvc4 and attempting to implement an AJAX search feature. However, I keep encountering an error message that says "The resource cannot be found." What am I doing incorrectly? Controller //Search [HttpPost] publ ...

Getting data from a document containing key value pairs

I have a collection of text files that are structured in a key-value pair format. "Site Code": "LEYB" "Also known as": "" "Location": "Pier Site, Poblacion del Sur, Villaba, Southern Leyte" "Contact person(s)": "" "Coordinates[1]": "11 ...

adjusting the Rails response format to JS for an asynchronous request

I'm attempting to implement an Ajax request that triggers an update when a radio button is clicked without needing to refresh the entire page. The definition of the update action in my controller seems a bit lacking in documentation within Rails docs ...

Is async/await necessary even if the outcome is not important to me?

Imagine I have an API call that performs X and I convert it into asynchronous code using async/await: export default async (req: NextApiRequest, res: NextApiResponse) => { let success = await sendEmail({ //... }); return res.status(200) ...