When the Json payload is lengthy, an Ajax request to an ASP.NET MVC Controller results in a 404 error

I am facing an issue with my ajax call that involves passing a json string to a controller action. When the content portion of the json is too long, or when the json string in general exceeds a certain length, the server returns a 404 error. However, if I shorten the content, the request resolves and completes correctly.

Initially, I thought this problem was due to the 8k limit of Microsoft's JavaScriptSerializer. I tried updating the MaxJsonLength parameter, but unfortunately, that did not solve the issue. Can someone please shed some light on what might be causing this problem?

Below is the snippet of code for my ajax request (Please note that this code utilizes Knockout.js)

 self.updatePost = function () {
            var postToUpdate = ko.toJS(self.selectedPost);
            postToUpdate.Content = $("#wmd-input").val();
            console.log(postToUpdate);

            $.getJSON('/blogs/posts/update', {post: ko.toJSON(postToUpdate)}, function(post) {
                if (post) {
                    // remove the selected post and add the updated post
                    self.posts.remove(self.selectedPost());
                    var updatedPost = new Post(post);
                    self.posts.unshift(updatedPost);
                    self.selectedPost(updatedPost);
                    $("#ghost-list li:first").trigger('click');
                    // show alert
                }
            });
        };

The following is the C# Controller Action:

 public JsonResult Update(string post)
    {
        var seralizer            = new JavaScriptSerializer();
        seralizer.MaxJsonLength  = int.MaxValue;
        seralizer.RecursionLimit = 100;
        var selectedPost         = seralizer.Deserialize<Post>(post);
        var student              = students.GetStudentByEmail(User.Identity.Name);
        var blog                 = db.Blogs.SingleOrDefault(b => b.StudentID == student.StudentID);
        var postToUpdate         = blog.BlogPosts.SingleOrDefault(p => p.ID == selectedPost.ID);

        if (postToUpdate != null)
        {
            // update the post fields
            postToUpdate.Title       = selectedPost.Title;
            postToUpdate.Slug        = BlogHelper.Slugify(selectedPost.Title);
            postToUpdate.Content     = selectedPost.Content;
            postToUpdate.Category    = selectedPost.Category;
            postToUpdate.Tags        = selectedPost.Tags;
            postToUpdate.LastUpdated = DateTime.Now;
            if (selectedPost.Published)
            {
                postToUpdate.DatePublished = DateTime.Now;
            }
            // save changes
            db.SaveChanges();

            var jsonResult = Json(seralizer.Serialize(selectedPost), JsonRequestBehavior.AllowGet);
            jsonResult.MaxJsonLength = int.MaxValue;
            return jsonResult;
        }
        return Json(false, JsonRequestBehavior.AllowGet);
    }

Answer №1

Have you considered utilizing the post method for this task:

$.post('/blogs/posts/update', {post: ko.toJSON(postToUpdate)}, function(post) {
    if (post) {
        // Remove the selected post and insert the updated post
        self.posts.remove(self.selectedPost());
        var updatedPost = new Post(post);
        self.posts.unshift(updatedPost);
        self.selectedPost(updatedPost);
        $("#ghost-list li:first").trigger('click');
        // Display an alert
    }
 }, 'json');

Answer №2

Give this a shot in your web configuration file

<system.web.extensions>
<scripting>
  <webServices>
    <jsonSerialization maxJsonLength="500000000"/>
  </webServices>
</scripting></system.web.extensions>

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

Displaying JavaScript Array Elements in an Aligned Table Format

Unfortunately, I accidentally deleted my previous post and now need to repost it. I have a code that is functioning well, thanks to the great help I received here. However, the output of the array players is not neatly aligned with each other in a table f ...

Vue.js is not properly synchronizing props in a child component when the parent component is updating the property

When it comes to communication between components, my structure looks something like this: <div id=chat-box> <div class="wrapper"> <div> <chat-header></chat-header> <message-container :chat="chat"></message ...

"Implementing conditional evaluation for pixel units in AngularJS using ng-style

Looking to adjust the style of an element based on its height. For example, if the height is less than X, apply 'style 1'; otherwise, apply 'style 2'. The syntax appears to be correct, but accurately evaluating the height property in p ...

Utilizing ng-repeat $index for locating an element within an array

Within my $scope, there is a property called $scope.cars, which is an array of cars. Users have the ability to delete a car from this array. When calling the delete function deleteThis, I pass the $index parameter created by ng-repeat. However, in the Ja ...

The SvelteKit server successfully loaded data, displaying it on the sources/index page in the Chrome

I am currently in the process of developing a basic web application that utilizes self-hosted Pocketbase on the backend and SvelteKit as a meta framework. Recently, I discovered that the data loaded by my server is visible in the browser's sources/in ...

How to successfully pass data in a Rack::Test while testing an AJAX POST request?

I'm currently utilizing the Rack::Test library for testing my application and am in need of testing the AJAX data posting functionality. Here is a snippet from my test: describe 'POST /user/' do include Rack::Test::Methods it 'sho ...

Updating state before and after making an API request

I have implemented an asynchronous function with prevState in my code. The purpose of using prevState is twofold: 1) updating a deeply nested object and 2) sending data to an API based on the current state. Asynchronous programming is utilized for the API ...

What causes a browser to redirect when trying to update the value of the alt field in a Wordpress media image?

Attempting to create a bookmarklet for the Wordpress image gallery manager that triggers the sidebar when an image is clicked. The sidebar contains fields for alt text (input), legend, and description (both textarea). <a href="javascript:var t=document ...

React state not being updated by setState method

Here's the situation: let total = newDealersDeckTotal.reduce(function(a, b) { return a + b; }, 0); console.log(total, 'tittal'); //displays correct total setTimeout(() => { this.setState({ dealersOverallTotal: total }); }, 10); cons ...

Is there a way to retrieve a single value using AJAX instead of returning the entire HTML page?

(edited after initial version) I'm facing an issue where my AJAX call is returning the header.php page instead of just the $result value which should be 0 or 1. The AJAX function calls generateTicket.php, where I want to generate tickets only if no o ...

Are programmatic clicks distinguishable from manual clicks in JQuery?

Currently, I am in the process of creating selectable and draggable elements for a table. You can test the functionality by following this JsFiddle link (please try vertically selecting). Initially, the selection works well but upon trying to select for th ...

Ways to present a Nuxt page as a reply from an express route

How can I achieve a similar functionality to res.render on a Nuxt page? The project is using the nuxt-express template, which combines Nuxt and Expressjs. Although Nuxt provides nuxt.render(req, res) and nuxt.renderRoute, I am having trouble making it wo ...

The JS content failed to load into the HTML page

I need help creating a workout tracker using two JS files. The main.js file is responsible for loading content from the second file (workoutTracker.js) into the index.html. However, I'm facing an issue where the content is not being displayed on the p ...

The Node application seems to be encountering an issue when attempting to handle

Whenever I click a button on my page in Node using Express, my JavaScript file sends the following request: toggleCartItem = index => { http = new XMLHttpRequest(); http.open("POST", `/cart_item/${index}`, true); http.send(); } Th ...

Experiencing the error message "Uncaught TypeError: Cannot read property 'push' of undefined" unexpectedly popping up at random intervals

Hey there, I've encountered an issue while trying to fetch data from a URL and populate it into an array. The process involves pushing the fetched data into the "data" property of each element in the array, and then repeating this process recursively. ...

Searching in real-time with ajax in CodeIgniter framework is a seamless and efficient process

I'm a beginner in CodeIgniter and eager to learn. Currently, I'm facing an issue where the data is not being populated on the search page. In the model: function fetch_data($query) { $this->db->select('*'); $this-> ...

Pausing repetitive HTTP requests in an Angular 6 project within a do while loop

While waiting for the completion of one API call, I am recursively consuming an external API. The http calls are being made using import {HttpClient} from '@angular/common/http' As a newcomer to the framework, there may be something wrong in the ...

What is the purpose of sorting an object using the sequence defined in an array?

Have you ever wondered how the sortWeekFunction function can rearrange an object based on a predefined array order? It may seem complex at first glance, but let's break down how this code actually works. const weeksArr = ['sunday', ' ...

I provided Array.Filter with a function instead of a predicate, and surprisingly it gave back the entire array. How is that possible?

I encountered an unusual scenario where I passed a function instead of a predicate to Array.filter. This function modified individual student objects and the filter returned the whole array. This led me to question, why is this happening? According to co ...

AngularJs can manipulate the visibility of elements by showing or hiding them based

I wanted to create a simple hover effect where only the child element of each <li> is displayed when I hover over it. Initially, I set up a ng-show value of false for all elements and tried to change it to true on hover. However, this caused all chil ...