Sending a JSON object as a map through AJAX to an MVC controller

I am looking to send a map (dictionary) to the MVC controller along with a string parameter.

var reportName= 'ReportName';

    var FilterValues = new Map([
[0, "value1"],
[1, "value2"],
[2, "value3"],
]);

var model = { reportName: reportName, FilterValues: JSON.parse(FilterValues) };
        $.ajax({
            url: '/Reports/ExportReport/',
            type: 'POST',
            contentType: "application/json",
            data: model,
        success: function(){
            alert('success');
        }, 
        error: function(){
            alert('failure');
        }
    });


 public void ExportReport(string reportName, Dictionary<int, string> FilterValues)

        {

I attempted this approach using an Object instead of a map. Although it returned success, it did not hit the controller.

let FilterValues = {
            1: "value1",
            2: "value2",
            3: "value3",
        };

        var report = 'test';
      //  var data = ('#DesignationReport').DataTable().$('input,select,textarea').serialize();
        var model = { reportName: report, FilterValues: FilterValues };

This marks my latest attempt.

Answer №1

To work around the lack of support for ES2015 constructs like Map in JSON, we can create a custom class as shown below:

 public class ViewModel
    {
        public List<FilterValue> FilterValues { get; set; }
        public string ReportName { get; set; }
    }

    public class FilterValue
    {
        public int Id { get; set; }
        public string Value { get; set; }
    }

The post method will look something like this:

[HttpPost]
        public ActionResult ExportReport(ViewModel model)
        {
            var report = model.ReportName;
            var values = model.FilterValues;
            return new EmptyResult();
        }

Next, include these scripts in your view:

@section scripts{
    <script>
        $(function () {
            var reportName = 'ReportName';
            var filterValues = [];

            filterValues.push({ 'Id': 0, 'Value': 'value1' });
            filterValues.push({ 'Id': 1, 'Value': 'value2' });
            filterValues.push({ 'Id': 2, 'Value': 'value3' });

            var model = JSON.stringify({ ReportName: reportName, FilterValues: filterValues});
            $.ajax({
                url: '/Home/ExportReport/',
                type: 'POST',
                contentType: "application/json",
                data:  model,
                success: function () {
                    alert('success');
                },
                error: function () {
                    alert('failure');
                }
            });
        });
    </script>
}

Answer №2

When setting up your model in the MVC pattern, make sure to structure it like this:

        public class SpecialDataModel
        {
            public string nameOfReport { get; set; }
            public List<FilterItem> Filters { get; set; }
        }

        public class FilterItem
        {
            public int uniqueId { get; set; }
            public string filterValue { get; set; }
        }

Your controller method should be configured as follows:

        [HttpPost]
        public void GenerateReport(SpecialDataModel data)
        {



        }

Ensure that your AJAX request contains the necessary data setup:

var reportTitle = 'New Report';
var Filters = [];
Filters.push({'uniqueId': 0, 'filterValue': 'valueA'});
Filters.push({'uniqueId': 1, 'filterValue': 'valueB'});
Filters.push({'uniqueId': 2, 'filterValue': 'valueC'});

var modelData = JSON.stringify({ 'nameOfReport' : reportTitle, 'Filters' : Filters });

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

Associate keys with strings and then map them to a specific type of strings in Typescript

I am endeavoring to develop a React component that extends the Octicons icon library available from Github at @githubprimer/octicons-react. One of the components exported by the library is the iconsByName type, which has the following structure: type ico ...

Adjusting a NodeJS module for easier integration into codebases

I have organized some functions in a file within a node module structure... Here are the files and folder structure I created: - package.json - README.md - LICENSE.md - code |_______ code.js Currently, to use these functions, I include them like th ...

The performance of the Ajax Jquery remove function leaves something to be desired

My table has items with a delete button for each row. To achieve this, I created the following Ajax function: $(document).ready(function() { $(".destroy-device").click(function(e) { e.preventDefault(); var id = $(this).attr("data-id"); $.aj ...

Only one of the two scripts is functioning as intended

I'm facing an issue with two different scripts - the first one doesn't seem to work while the second one does. Oddly enough, when I remove the second script, the first one starts working. Can you help me find a solution? <script> // Ta ...

Using JavaScript within WordPress to achieve a seamless scrolling effect

I am seeking to implement a Smooth Scroll effect on my website located at . The site is built on WordPress and I am facing difficulty in connecting JavaScript/jQuery in WordPress. I have come across various WordPress plugins, but they either do not meet my ...

Top Jquery File Upload Tool (ajax)

I've come across various Jquery-Ajax-Upload scripts, but I'm curious to know which one you currently find to be the most stable and reliable? Thanks in advance! Peter ...

Incorporating stick-to-top scroll functionality using AngularJS and ng

I am trying to implement a 'sticky' scroll on dynamic content. My current working example can be found here. It seems to be working, but I encounter a small 'flicker' when new items are appended. This issue seems to be related to the se ...

Uploading an image using ajax with multer

When using Multer to upload an image file to my Node server, I keep getting 'undefined' when trying to use ajax to send the image. Ajax : image = $("#input-file-img").val() const data = new FormData(); data.appe ...

Displaying HTML content from a Vuejs response within a Dialog box

After receiving a response from the server via a REST request in HTML format, I have saved it in a data:[] variable. When I log this data on the console, it appears as raw HTML code. This reply is currently stored as a String, and my challenge now is to co ...

What could be the reason for the history.length being 2 on the initial page?

Why is it that when I open a new browser window and load a page in it, the history.length property is always 2 in both Chrome and Firefox? You can test this phenomenon yourself by visiting the following link: http://jsbin.com/amiyaw ...

Is there a way to generate a POJO object based on the provided JSON data?

Looking to create Plain Old Java Objects (POJOs) for the JSON data obtained from the API located at https://developers.google.com/qpx-express/v1/trips/search Encountering an issue when trying to generate POJOs using . An error is triggered at line 5 with ...

Creating personalized serialization for bson and JSON in Golang using mgo libraries

I am working with a custom type in Golang called Base64Data: type Base64Data []byte To facilitate unmarshalling a base64 encoded string into this type, I implemented the following method: func (b *Base64Data) UnmarshalJSON(data []byte) error { if le ...

Map Infobox appearing on page load

I am working on a Google map project where markers and info boxes dynamically populate when the user clicks on the map. However, I now need the info box to be loaded initially when the map loads, without requiring a click event. I have tried writing some c ...

Submitting an ASP.NET MVC3 form via ajax allows you to bypass the default behavior and still preserve client-side validation

Is there a way to modify the behavior of form submission using ajax while still keeping client side validation in ASP NET MVC3? I am struggling to override the default action that occurs when the form is posted. Even though I have a jquery function set up ...

The slideUp function is not functioning as expected

I am trying to implement a slideUp effect on my webpage. Here is the code within my <body> tag: <script> $('#slide_up').click(function(){ $('p.text_study').slideUp('slow', function() { $ ...

The issue of the JQuery method failing to function properly on a button arises when the button is added

Upon loading a HTML page containing both HTML and JavaScript, the code is structured as shown below: <button id="test"> test button </button> <div id="result"></div> The accompanying script looks like this (with jQuery properly in ...

Utilize ReactJS and AJAX to easily upload images

Having trouble with uploading an image through a form to a url/api. When I submit the form, I'm calling the handleImgUpload() method. The issue is that the request being sent is coming back empty. Seems like there might be a problem with new FormData ...

Get an Array Using AJAX in PHP and JavaScript

Section 1 I want to retrieve an Array from PHP and use it in JavaScript. I have created a file using the fwrite function in PHP, then included that file in my next .load method inside a Div. The new PHP file contains an "include 'somefile.php';" ...

Angular (TypeScript) time format in the AM and PM style

Need help formatting time in 12-hour AM PM format for a subscription form. The Date and Time are crucial for scheduling purposes. How can I achieve the desired 12-hour AM PM time display? private weekday = ['Sunday', 'Monday', &apos ...

Analyzing this strange PHP response for parsing

Having trouble efficiently parsing a JSON mixed array response from an API, particularly accessing the price and name property. [{"Price":10,"Active":null,"Status":100,"Name":"ID"}] Attempted using json_decode/json_encode with foreach loop but still unab ...