How can I send my response as JSON in the controller in Asp.net?

Whenever I use toastr for form notifications, I always seem to receive an error message even though the data is successfully saved in the database. I suspect that the error may be stemming from the controller because I am not sending back in JSON format. Any help would be greatly appreciated.

-----Controller : ---------------

        public ActionResult CreateNewRentals(NewRentalDto newRental)
    {
        var hour = DateTime.Now;
        var customer = _context.Customers.Single(
            c => c.Id == newRental.CustomerId);

        var movies = _context.Movie.Where(
            c => newRental.MovieId.Contains(c.Id)).ToList();

        foreach (var movie in movies)
        {
            if (movie.NumberAvailable == 0)
               return BadRequest("le film est introuvable");

            movie.NumberAvailable--;
            var rental = new Rental
            {

                Customer = customer,
                Movie = movie,
                DateRented = DateTime.Now
            };

            _context.Rentals.Add(rental);

        }
        _context.SaveChanges();
        return Ok();
    }

----------------La view --------------------

<script type="text/javascript">




    $(document).ready(function () {

        var vm = {
            movieId: []
        };
        var customers = new Bloodhound({
            datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
            queryTokenizer: Bloodhound.tokenizers.whitespace,
            local: customers,
            remote: {
                url: '/api/customers?query=%QUERY',
                wildcard: '%QUERY'
            }
        });

        $('#customer').typeahead({
            hint: true,
            highlight: true,
            minLength: 1
        }, {
            name: 'customers',
            display: 'name',

            source: customers
        }).on("typeahead:select", function (e, customer) {
            vm.customerId = customer.id;



        });

        /* MOVIES */

        var movies = new Bloodhound({
            datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
            queryTokenizer: Bloodhound.tokenizers.whitespace,
            remote: {
                url: '/api/movies?query=%QUERY',
                wildcard: '%QUERY'
            }
        });
        $('#movie').typeahead({

            hint: true,
            highlight: true,
            minLength: 1
        }, {
            name: 'movies',
            display: 'name',
            source: movies
        }).on("typeahead:select", function (e, movie) {
            $("#movies").append("<li class='list-group-item'>" + movie.name + "</li>");
            $("#movie").typeahead("val", "");
            vm.movieId.push(movie.id);
        });
        $("#newRental").submit(function (e) {

            e.preventDefault();
            $.ajax({
                url: "/api/newRentals",
                method: "POST",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(vm),
                success: function (data) {
                    toastr.success(' successfully!');

                },
                error: function () {
                    toastr.error( 'error!');
                }
            });

        });
    });



</script>

Answer №1

Ensure you are providing a value when using the Ok() result. You can pass it like this: return Ok(OBJECT HERE) or return new JsonResult(OBJECT HERE). Remember that Ok() returns a HTTP status of 200.

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

Using JAVA to convert a QueryString into JSON

How can I transform the querystring "id=1&location=india" into JSON format {"id":"1","location":"india"} using Java? Currently, I am working with Spring 4.0.3. ...

Determine if a specific date occurred at least one day ago using momentjs

Is there a way to determine if a specific date is at least one day (24 hours) in the past using momentjs? For example: const currentDate = moment() const isAtLeastOneDayAgo = currentDate.subtract(dateToVerify) > 1 // How can this be done? ...

How to insert a JSON string into a MongoDB database using Scala script

Looking for assistance with inserting the following JSON string into MongoDB: {"card_id" : 75893645814809,"cust_id": 1008,"card_info": {"card_type" : "Travel Card","credit_limit": 126839},"card_dates" : [{"date":"1997-09-09" },{"date":"2007-09-07" }]} If ...

Custom cellRenderer prevents Ag Grid's autoHeight and wrapText features from functioning properly

I've been attempting to adjust the formatting of a long cell value by wrapping the text. According to the documentation, setting autoHeight=true and wrapText=true works fine without any cellRenderer components. However, when using a cellRendererFramew ...

Saving videos for offline viewing in a Vue Progressive Web App with Vue.js 3

I'm having a bit of an issue with my Vue 3 and Typescript setup. I've created a PWA where I display videos, which works perfectly online. However, when I try to access them offline, the videos don't load properly. I have stored the videos in ...

How to Store and Retrieve User-specific Data using Express and Mongoose?

Currently, I am developing a small single-page application that allows users to login using PassportJs and Mongoose. One of the main features I am working on is enabling users to log in and have a unique todo/task list associated with each user. I succes ...

Checking if a date is before another date in MomentJS without considering the

Recently, I've been utilizing momentJS to identify future dates without a specific day. Below is the code I've been working with along with the outcome: moment('09/2010').isBefore(moment().format('MM/YYYY'), 'day') ...

"Utilize Regular Expressions to conceal part of a text string with a

Looking for a way to conceal part of a string using JavaScript? For example, wanting to mask the second and third segments of a credit card number like this using regex: 4567 6365 7987 3783 → 4567 **** **** 3783 3457 732837 82372 → 3457 ****** 82372 ...

The Vue plugin encountered an issue with an error message stating "Uncaught SyntaxError: Unexpected token

I'm excited to dive into using vue for my upcoming project. I decided to incorporate Hooper, an image carousel, and went ahead to install it using npm install hooper. To implement it in my script file, I included the following code: import { Hooper ...

What is the best way to store JSON data in Mongoose database?

I have some json data that I need to store in a mongoose database, but I'm struggling with how to structure my mongoose schema. data: { 'posts[0][commentId]': '0', 'posts[0][id]': '1', 'posts[0][post ...

Running javascript code after the completion of the render method in Reactjs

I am working with a ReactJS component: const com1 = React.createClass({ render: function() { return ( <a href='#'>This is a text</a> ); } }); I am looking to run some Javascript/jQuery code once the rendering ...

Eliminating characteristics and rejuvenating the component

I have divs on my webpage that I want to keep hidden until a specific element is clicked. When trying to hide them, I encountered three options: visibilty: hidden - I didn't like this because the hidden div still took up space in the layout. displa ...

Tips for refreshing jQuery to ensure it functions smoothly for subsequent tasks

I am facing an issue with running a second process under JQuery, as shown in the code snippet below: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <script type=" ...

Displaying live data from an XMLHttpRequest in a Vue component in real-time

I'm currently working on implementing lazy loading for a list of posts fetched from the WordPress REST API. My goal is to load additional news stories upon clicking an HTML element. However, I'm facing issues with accessing the original Vue inst ...

Is there a way to transform a circular structure into JSON format?

I retrieved data from the database and now I need to format it, but I encountered the following error: TypeError: Converting circular structure to JSON --> starting at object with constructor 'NativeConnection' | property ' ...

1. "Ensuring the URL of a New Tab Using WDIO"2

During my testing scenario: Navigate to link1 Click a button Open a new tab with link2 How should I verify the link2? I attempted using assert(browser).toHaveUrlContaining(''), but it only verified the link1, causing my test to fail. ...

BS Modal was improperly invoked, leading to an illegal instantiation

Currently, I am attempting to trigger a bootstrap Modal in Angular by utilizing the component instead of its HTML attribute. However, I am encountering an error (specifically, illegal invocation). Here is the code snippet from the component: @ViewChild(&a ...

What is the process for printing a formview page?

Is it possible to create a routine for printing pages with a formview table, similar to how it's done with a gridview? Can the existing routine be modified to work with formview by changing GridView1 to FormView1? Please note that this will only work ...

Issue with page scrolling while utilizing the Wow.js jQuery plugin

While using the Wow.js plugin for scroll animations, I encountered an issue on mobile phones. When reaching the Pricings section, scrolling becomes impossible for some reason. I am utilizing Bootstrap 3 in this project. Despite attempting to modify the an ...

Scrolling back to the top of the page using Jquery instead of a specific div

Check out the code for my project here. The isotope feature is functioning correctly, however, when clicking on the image, instead of scrolling to the navigation under the red box as intended, the page scrolls all the way to the top. If I modify the follo ...